将文本文件中的整数插入整数数组

Inserting integers from a text file to an integer array

我有一个包含一些整数的文本文件,我想将这些数字插入到该文本文件中的整数数组中。

 #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”。

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

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

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

我建议使用 std::vector<int> 而不是固定大小的数组:

 #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;
}