【问题标题】:Loop skips lines when reading data from a file into array C++将文件中的数据读入数组 C++ 时循环跳过行
【发布时间】:2017-10-25 23:12:14
【问题描述】:

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

【问题讨论】:

  • inFile.open 不是File
  • readin() 必须返回一个值。

标签: c++ arrays file loops fstream


【解决方案1】:

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

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++;

【讨论】:

    【解决方案2】:

    你可以这样做:

    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;
      

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 1970-01-01
      • 2016-04-21
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 2011-12-21
      • 2017-10-05
      相关资源
      最近更新 更多