在C++中读取文件直到行末?

9

如何读取一行的数据?我有一个名为“file.txt”的文本文件,内容如下:

1 5 9 2 59 4 6
2 1 2 
3 2 30 1 55

I have this code:

ifstream file("file.txt",ios::in);
while(!file.eof())
{
    ....//my functions(1)
    while(?????)//Here i want to write :while (!end of file)
    {
        ...//my functions(2)
    }

}

在我的函数(2)中,我使用来自行的数据,需要是Int类型而不是char类型。


为什么需要读取到行的结尾?而“行的结尾”是指第一行的结尾还是所有行的结尾? - David G
通过“行末”我指的是读取第一行,使用其中的数字执行必要操作,继续读取第二行……直至最后一行。 - user3050163
当前的任何答案有帮助吗?请给予反馈。 - David G
相反,你所描述的正是herohuyongtao代码的确切功能。也许你应该解释一下你认为他的示例有什么错误? - David G
我想提交一个答案,但首先我需要了解更多关于您正在尝试做什么的信息。herohuyongtao的答案遍历每一行,然后使用字符串流来迭代该行的整数。如果这对您不够满意,我需要更多详细信息才能明确要做什么。 - David G
显示剩余5条评论
4个回答

12

不要使用 while(!file.eof()),因为eof()只有在读到文件末尾后才会被设置。它并不能指示下一次读取将是文件的末尾。相反,你可以使用while(getline(...))结合istringstream来读取数字。

#include <fstream>
#include <sstream>
using namespace std;

// ... ...
ifstream file("file.txt",ios::in);
if (file.good())
{
    string str;
    while(getline(file, str)) 
    {
        istringstream ss(str);
        int num;
        while(ss >> num)
        {
            // ... you now get a number ...
        }
    }
}

你需要阅读 为什么在循环条件中使用iostream::eof被认为是错误的?


如果我使用getline,我必须从int转换为char,但我需要数据是int!!! - user3050163
1
@user3050163 已更新。 - herohuyongtao
(getline(file,str))没有工作 错误:无法将istream转换为char - user3050163
@user3050163 它应该能正常运行,我刚在 ideone 上测试过了。 - herohuyongtao
@herohuyongtao 它可以运行,但结果是错误的。它混淆了三行中的数字。 - user3050163
显示剩余2条评论

2

关于读到行末的问题,可以使用std::getline

然而,你还有另一个问题,就是循环时使用了while (!file.eof()),但这很可能不会按照你的预期工作。原因是直到你尝试从文件结束后读取数据时才会设置eofbit标记。相反,你应该使用while (std::getline(...))等方式。


@user3050163 读入一个 std::string,放入一个 std::istringstream 中,使用输入运算符 >> 循环获取每个以空格分隔的值。 - Some programmer dude
或者在读取该行并将其放入 std::istringstream 后,使用 std::istream_iteratorstd::copy,使用 std::back_inserter 将值直接放入 容器 中。 - Some programmer dude

1
char eoln(fstream &stream)          // C++ code Return End of Line
{
    if (stream.eof()) return 1;     // True end of file
    long curpos;    char ch;
    curpos = stream.tellp();        // Get current position
    stream.get(ch);                 // Get next char
    stream.clear();                 // Fix bug in VC 6.0
    stream.seekp(curpos);           // Return to prev position
    if ((int)ch != 10)              // if (ch) eq 10
        return 0;                   // False not end of row (line)
    else                            // (if have spaces?)
        stream.get(ch);             // Go to next row
    return 1;                       // True end of row (line)
}                                   // End function

你可以使用这个来读取一行的剩余部分:string line; getline(stream, line);。我用它来读取文件的剩余部分。 - mathengineer

0
如果你想将它写成一个函数以便在其他地方调用,你可以使用向量。这是我用来逐个返回整数元素的函数,用于读取此类文件。
vector<unsigned long long> Hash_file_read(){
    int frames_sec = 25;
    vector<unsigned long long> numbers;
    ifstream my_file("E:\\Sanduni_projects\\testing\\Hash_file.txt", std::ifstream::binary);
    if (my_file) {

        //ifstream file;
        string line;

        for (int i = 0; i < frames_sec; i++){
            getline(my_file, line);
            numbers.push_back(stoull(line));
        }

    }
    else{
        cout << "File can not be opened" << endl;
    }
    return numbers;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接