在 c++ 中从 txt 文件读取到结构

Reading from a txt file to a struct in c++

本文关键字:读取 结构 文件 txt c++ 中从      更新时间:2023-10-16

为什么我的代码中的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 从未设置。