【问题标题】:How to create an array by reading a file in c++ if every line contains an integer?如果每一行都包含一个整数,如何通过在 C++ 中读取文件来创建数组?
【发布时间】:2020-11-22 04:31:46
【问题描述】:

在 C++ 中,我应该读取一个文件,其中每一行都包含一个整数,并将每个整数传输到一个数组中。我尝试使用 getline() 函数计算行数。并创建了数组,但是当我计算行数时,它会消耗,如果我再次使用 getline() 函数,它将不起作用。我该怎么办?谢谢。

ifstream inFile( fileName );
if ( inFile.is_open() ) {
    int size = 0;
    string line;
    while( getline(inFile, line)) 
         size++;
    int* array = new int [ size ];
    while ( getline( inFile, line )) {
         ....
    }
}
The code does not enter the second while.

【问题讨论】:

  • 您应该将读取的整数添加到std::vector
  • 请分享您描述的代码。
  • 编辑问题,不要使用 cmets。另外,请确保发布minimal reproducible example

标签: c++ arrays file


【解决方案1】:

在第二个 while 循环之前重置 fstream

inFile.clear();
inFile.seekg(0, std::ios::beg);
while ( getline( inFile, line )) {
....

【讨论】:

    【解决方案2】:

    当这个循环完成时:

    while( getline(inFile, line)) 
        // ...
    

    inFile 已用尽,没有更多数据可从中读取。

    一种选择是再次打开文件,然后从中读取。但是,这很浪费,因为您可以跟踪您第一次从文件中读取的数字:

    std::vector<int> v;
    int i;
    while (inFile >> i)
      v.push_back(i);
    

    现在您拥有一个容器中的所有数字,您无需再次从文件中读取。

    请注意,我使用的是 std::vector 而不是数组,因为它更容易使用。

    如果您绝对必须使用数组,那么您可以读取文件一次以确定文件中有多少个整数:

    int i, count = 0;
    while (inFile >> i);
    

    然后为数组分配内存:

    int *array = new int[count];
    

    然后再次打开文件,读入数组:

    int i = 0;
    while (inFile >> array[i++]);
    

    【讨论】:

    • 效率不用担心。但是,我不能在这个作业中使用向量。我还有其他方法可以使用您的想法吗?
    • @MustafaYaşar 也添加了使用数组的解决方案。
    【解决方案3】:

    您可以将文件读入字符串,然后使用字符串而不是文件

    std::ifstream t("file.txt");
    std::stringstream buffer;
    buffer << t.rdbuf();
    std::string stringOfNumbers = buffer.str();
    

    然后从那里通过换行符拆分字符串,将拆分的字符串解析为整数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 2015-05-12
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多