简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM