将数据从文件放入字符数组不会在最后数据停止
Putting Data From File To Char Array Doesn't Stop At Last Data
我对使用类很生疏,并且正在复习使用它们。 我遇到了一个问题,我试图使用一个简单的程序从包含简单数字的文件中检索数据(在本例中为"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++;
}
相关文章:
- 防止主数据类型C++的隐式转换
- 用于访问容器<T>数据成员的正确 API
- 嵌套在类中时无法设置成员数据
- 读取文件的最后一行并输入到链接列表时出错
- 如何在Qt TableView中将列的宽度调整为数据并将最后一部分拉伸在一起
- 缓冲区用不需要的数据填充 char 数组中的最后一个空格
- 计算列表中与线性链接列表中最后一个节点具有相同数据的节点的数量
- 将数据附加到 csv 文件,在最后一个条目之前而不是最后一个条目之后.C++
- 为什么OpenDDS在删除DataWriter时重新发送相同的最后一个数据
- 在 Getline C++ 上复制最后的数据
- 正确的数据结构,用于在C++中存储最后 n 个元素
- 将数据从文件放入字符数组不会在最后数据停止
- 我似乎无法在qt创建器中打印几行数据。程序覆盖除最后一行之外的所有输出
- C++ OpenMP:将 for 循环拆分为静态偶数块,并在最后连接数据
- 从文本文件中读取的对象数组中最后丢失的数据
- 在整型数组的最后一个元素中存储数据的问题
- 有一个很长的缓冲区,但只使用最后1GB字节的数据
- 在列表中搜索数据的最后一个实例
- 使用Rcpp返回数据帧,其中仅包含例如患者的最后观察结果
- Gnuplot:跳过最后一行/不完整的数据文件