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

标签 c++ arrays file loops fstream

我正在为我的 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++;

关于c++ - 将文件中的数据读入数组 C++ 时循环跳过行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46943410/

相关文章:

Python奇怪的语法

python - 在文件名中保存视频文件的时间和日期

wpf - wpf中的文件加载器

c++ - 模板的非类型参数

c++ - 删除 vector 时出现段错误

c++ - qt_screen 的编译问题

python - 组合和规范化来自多个多维数组的数据的最快方法

arrays - 如何查找数组是否包含对象

c# - 在 Silverlight 中编辑 XML 文件不起作用,但为什么?

c++ - std::sort() 的自定义元组比较器