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