如何读取包含未知大小的整数列表的文件

How to read file containing a list of integers with an unknown size

提问人:ROSBY ASIAMAH 提问时间:3/30/2021 最后编辑:Alan BirtlesROSBY ASIAMAH 更新时间:3/30/2021 访问量:289

问:

我想从一个包含 4 个整数的未知列表的文件中读取。所以文件的每一行都包含这样的内容:“12.0 43.0 19.0 77.0” 我想过使用二维数组,但我不知道文件的大小,因为它是一个非常大的文件。我最终将每一行都读为字符串并使用“while(!in_file.eof())”,这样我就可以到达文件的末尾,但问题是,我需要从每一行中单独获取数字。

Here's a snippet of my code

C++ 数组 ifstream eof

评论

0赞 463035818_is_not_an_ai 3/30/2021
为什么 iostream::eof 在循环条件中(即 while (!stream.eof()))被认为是错误的?
0赞 user4581301 3/30/2021
“while(!in_file.eof())”,这样我就可以到达文件的末尾。不幸的是,这通常会读取文件的末尾,因为它会在读取和查找文件末尾之前检查您是否已到达文件末尾。
1赞 463035818_is_not_an_ai 3/30/2021
12.0 43.0 19.0 77.0 不是整数
1赞 user4581301 3/30/2021
不要发布代码图像。它们很难搜索,对视障人士不透明,被防火墙阻止,并且难以编译。将代码以文本形式发布。您将在问题页面链接的帮助中找到有关如何设置其格式的建议,使其看起来不像垃圾。

答:

0赞 ArashV 3/30/2021 #1

您不需要知道文件中有多少行或每行中有多少个数字。

使用 std::vector< std::vector< int > > 存储数据。 如果在每一行中,整数用空格分隔,则可以迭代一串整数,并将它们一个接一个地添加到向量中:

#include <iostream>
#include <string>    
#include <stream>
#include <vector>
using namespace std;

int main()
{
    string textLine = "";
    ifstream MyReadFile("filename.txt");
    vector<vector<int>> main_vec;

    // Use a while loop together with the getline() function to read the file line by line
    while (getline(MyReadFile, textLine)) {
    
        vector<int> temp_vec; // Holdes the numbers in a signle line
        int number = 0;

        for (int i = 0, SIZE = textLine.size(); i < SIZE; i++) {

            if (isdigit(textLine[i])) {
                number = number * 10 + (textLine[i] - '0');
            }
            else { // It's a space character. One number was found:
                temp_vec.push_back(number);
                number = 0; // reset for the next number
            }
        }

        temp_vec.push_back(number); // Also add the last number of this line.
        main_vec.push_back(temp_vec); 
    }

    MyReadFile.close();

    // Print Result:
    for (const auto& line_iterator : main_vec) {
        for (const auto& number_iterator : line_iterator) {
            cout << number_iterator << " ";
        }

        cout << endl;
    }
}

提示:此代码仅适用于整数。对于浮点数,您可以轻松识别每行中空格的索引,获取 textLine 的子字符串,然后将此子字符串转换为浮点数。

评论

0赞 ROSBY ASIAMAH 3/30/2021
非常感谢您的帮助。
0赞 ArashV 3/31/2021
@rosby-asiamah YW,如果这个答案解决了你的问题,请将其标记为已选择。