在 c++ 中从 txt 文件读取到结构
Reading from a txt file to a struct in c++
为什么我的代码中的nr
变量递增到5以上?
当我测试 while 循环迭代的次数时,它的循环次数比我的数据文件中的元素多得多,我不明白为什么。
数据文件包含 - a 1 2 3 b
这是我的代码:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
struct SOMETHING
{
string string[10];
int int_1[100];
};
void main()
{
int nr = 0;
SOMETHING P;
ifstream D("data.txt");
while(!D.eof())
{
nr++;
if (nr == 1 || nr % 5 == 0)
{
D >> P.string[nr];
cout << P.string[nr] << " ";
}
D >> P.int_1[nr];
cout << P.int_1[nr] << " ";
}
D.close();
}
检查这个:
while(!D.eof())
{
nr++;
if (nr == 1 || nr % 5 == 0)
{
D >> P.string[nr];
cout << P.string[nr] << " ";
}
D >> P.int_1[nr];
cout << P.int_1[nr] << " ";
}
您的nr
变量超过 5 的原因是,每次成功读取每行后,您没有重置nr
。我不知道这是否是你想要的,但是你实现它的方式有一个问题(见下文):
您的结构元素显然有容纳 10 个元素的空间,但您只检查和存储索引 1 处的元素和 5 的倍数:
0, 1, 5, 10, etc.
正如@P0W在他的评论中指出的那样,使用
eof
方法是不好的做法。请改为使用 while 循环与std::getline
结合使用。
ifstream 的内部指针没有更新,所以 while 循环将无限期运行,因为 eofbit 从未设置。
相关文章:
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- 从只读内存中读取结构
- 从包含 IP 标头片段的二进制文件中读取结构的最佳方法是什么
- 读取结构化文件
- CPP 在读取结构数据时无限循环错误?
- 打开文件以读取结构数组
- 无效操作数以二进制读取结构的阵列
- 读取结构数组时出错
- 如何从另一个类读取结构成员
- 读取结构 -- uint32 不命名类型
- 从流或字节中读取结构时遇到问题
- 读取结构C++二进制文件的运行时错误
- 从二进制文件读取结构数据时获取垃圾值
- 在 c++ 中向二进制文件写入/读取结构
- 在C++文件中写入和读取结构体的三维矢量
- C++按字段读取结构,并将结构直接写入流
- 从LISP的套接字中读取c++结构
- 读取结构化二进制文件c++
- C++二进制文件正在读取结构
- 从CArchive保存的二进制数据中读取结构数组