将文件中的数据读入数组 C++ 时循环跳过行

Loop skips lines when reading data from a file into array C++

我正在为我的 CS 1 class 开发一个项目,我们必须创建一个函数,将文件中的数据读取到数组中。但是,当它运行时,它只会读取每隔一行数据。

文件包含 22 3 14 8 12,我得到的输出是:3 8 12

非常感谢任何帮助。很抱歉,如果这个问题已经得到解答,我找不到了。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int readin();

int main() {
  readin();
  return 0;
}

int readin(){
  ifstream inFile;
  int n = 0;
  int arr[200];

  inFile.open("data.txt");

  while(inFile >> arr[n]){
    inFile >> arr[n];
    n++;
  }

  inFile.close();

  for(int i = 0; i < n; i++){
    cout << arr[i] << " " << endl;
  }
}

原因是您在条件查询中从文件流中读取:

while(inFile >> arr[n]) // reads the first element in the file

然后再次读取并在循环中重写这个值:

{
    inFile >> arr[n];  // reads the next element in the file, puts it in the same place
    n++;
}

就这样:

while(inFile >> arr[n]) n++;

你可以简单地这样做:

while(inFile >> arr[n]){
    n++;
}

但是如果文件中值的数量大于数组大小怎么办? 那么你面临的是undefined behavior.

  • 我推荐使用vectors:

    std::vector<int> vecInt;
    int value;
    
    while(inFile >> value)
       vecInt.push_back(value);
    
    for(int i(0); i < vecInt.size(); i++)
        std::cout << vecInt[i] << std::endl;