【问题标题】:Inserting integers from a text file to an integer array将文本文件中的整数插入整数数组
【发布时间】:2017-03-11 13:58:07
【问题描述】:

我有一个填充了一些整数的文本文件,我想从这个文本文件中将这些数字插入到一个整数数组中。

 #include <iostream>
 #include <fstream>

 using namespace std;

 int main(){

  ifstream file("numbers.txt");
  int nums[1000];

  if(file.is_open()){

     for(int i = 0; i < 1000; ++i)
     {
        file >> nums[i];
     }
  }

  return 0;
}

而且,我的文本文件逐行包含整数,例如:

102
220
22
123
68

当我尝试使用单个循环打印数组时,除了文本文件中的整数之外,它还会打印很多“0”。

【问题讨论】:

  • 使用std::vector&lt;int&gt; 让您的生活更轻松。
  • “当我尝试打印数组时” - 您向我们展示的代码并没有这样做。看起来怎么样?
  • @JesperJuhl 只是一个 for 循环,它使用 cout 打印直到数组末尾的数字
  • @BK。你如何确定结局?与您输入输入的方式相同吗?请始终提供能重现您的问题的minimal reproducible example。最好也添加输出代码。
  • @πάνταῥεῖ 完全正确。

标签: c++ arrays file fstream


【解决方案1】:

始终检查文本格式提取的结果:

if(!(file >> insertion[i])) {
    std::cout "Error in file.\n";
}

问题是您的文本文件不包含 1000 个数字吗?

我建议使用 std::vector&lt;int&gt; 而不是固定大小的数组:

 #include <iostream>
 #include <fstream>
 #include <vector>

 using namespace std;

 int main(){

  ifstream file("numbers.txt");
  std::vector<int> nums;

  if(file.is_open()){
     int num;
     while(file >> num) {
         nums.push_back(num);
     }
  }

  for(auto num : nums) {
      std::cout << num << " ";
  }

  return 0;
}

【讨论】:

  • 我确定该文件包含 1000 个整数。谢谢你的建议。我会尝试这种方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 2011-04-14
相关资源
最近更新 更多