将整数从文本文件插入到整数数组

Inserting integers from a text file to an integer array

本文关键字:整数 数组 插入 文本 文件      更新时间:2023-10-16

我有一个装有一些整数的文本文件,我想将这些数字插入此文本文件中的整数数组。

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