gpt4 book ai didi

c++ - 将文件中的数据放入字符数组不会在最后一个数据处停止

转载 作者:行者123 更新时间:2023-11-30 03:44:28 24 4
gpt4 key购买 nike

我对使用类感到生疏,正在温习它们的使用。我遇到了一个问题,我试图使用一个简单的程序从一个包含简单数字(在本例中为“1234”)的文件中检索数据。

#include <iostream>
#include <fstream>

class hold
{
public:
void enter();
hold();
private:
char x[50];
};

hold::hold()
{
x[50] = NULL;
}

void hold::enter()
{
std::ifstream inFile;
inFile.open("num.txt");
int pos = 0;
while(inFile.good())
{
inFile >> x[pos];
pos++;
}

std::cout << "strlen(x) = " << strlen(x) << std::endl;
for(int i = 0; i < strlen(x); i++)
{
std::cout << x[i] << " ";
}
std::cout << std::endl;
}

int main()
{
hold h;
h.enter();
system("pause");

return 0;
}

输出是:

strlen(x) = 50;
1 2 3 4 (following a bunch of signs I do not know how to print).

自从我一直练习类(class)以来已经快一年了,我不记得在类里面使用过字符数组。谁能告诉我这个文件在“4”之后没有终止的问题在哪里?我试过使用 if 语句来中断 while 循环 if "x[pos] == '\0',但它也不起作用。

最佳答案

你没有终止你的字符串并且你有未定义的行为,因为 strlen 正在命中从未初始化的数组元素。试试这个:

while( pos < 49 && inFile >> x[pos] )
{
pos++;
}
x[pos] = '\0';

请注意,循环后的 pos 现在将与 strlen(x) 返回的相同。

如果您不需要以 null 结尾的字符串,则只需使用 pos 而不是 strlen(x) 而无需终止,但在这种情况下您需要避免使用任何依赖于空终止字符串的字符串函数。

您的构造函数中也有堆栈粉碎问题(未定义的行为):

hold::hold()
{
x[50] = NULL;
}

这可不行。不允许修改超出数组末尾的内存。如果你想将它归零,你可以这样做

memset( x, 0, sizeof(x) );

或者在 C++11 中:

hold::hold()
: x{ 0 }
{
}

关于c++ - 将文件中的数据放入字符数组不会在最后一个数据处停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35422561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com