将数据从文件放入字符数组不会在最后数据停止

Putting Data From File To Char Array Doesn't Stop At Last Data

本文关键字:数据 最后 字符 文件 数组      更新时间:2023-10-16

我对使用类很生疏,并且正在复习使用它们。 我遇到了一个问题,我试图使用一个简单的程序从包含简单数字的文件中检索数据(在本例中为"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).

自从我一直练习课程以来已经快一年了,我不记得在课堂上使用过字符数组。 谁能告诉我我在哪里搞砸了这个文件在"4"之后没有终止? 我尝试使用 if 语句来打破 while 循环,如果"x[pos] == '\0',但它也没有用。

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

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

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

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

构造函数中还有一个堆栈粉碎问题(未定义的行为(:

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

这是不行的。 不允许修改超过阵列末尾的内存。 如果你想把它归零,你可以做

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

或者在 C++11 中:

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

strlen需要一个以空值结尾的字符串。由于x不是以 null 结尾的,因此将其传递给 strlen未定义的行为

幸运的是,您不需要调用 strlen ,因为您有变量 pos 来计算 x 中的活动条目数:

std::cout << "length of my string = " << pos << std::endl;
for(int i = 0; i < pos ; i++) {
    std::cout << x[i] << " ";
}
除了

pos-1之外,有没有办法解释这个额外的字符?

是的,更好的方法是仅在您知道字符输入成功时才递增pos

while(inFile >> x[pos]) {
    pos++;
}