Search code examples
c++arraysfilefstream

Inserting integers from a text file to an integer array


I have a text file filled with some integers and I want to insert these numbers to an integer array from this text file.

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

And, my text file contains integers line by line like:

102
220
22
123
68

When I try printing the array with a single loop, it prints lots of "0" in addition to the integers inside the text file.


Solution

  • Always check the result of text formatted extraction:

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

    Can it be the problem is your text file doesn't contain 1000 numbers?

    I'd recommend to use a std::vector<int> instead of a fixed sized array:

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