循环在将数据从文件读取到数组C++时跳过行

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

本文关键字:C++ 数组 读取 数据 文件 循环      更新时间:2023-10-16

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

该文件包含 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;