c++ - Read a text file containing random sized integers separated by a space -
c++ - Read a text file containing random sized integers separated by a space -
my text file contains integers like: 123 879709789 43536 8768768
i want read whole number in 1 array index array[1]=123 array [2]=879709789.
here's i've tried:
ifstream myfile("numbers.txt"); if (myfile.is_open()) { while ( myfile.good() && !myfile.eof() ) { for(i=1; i<myfile.eof(); i++) { myfile >> ar[i]; if(ar[i]=="") { i++; } } } }
like this:
#include <vector> #include <fstream> #include <iterator> std::ifstream infile("myfile.txt"); // or utilize `std::cin` std::vector<int> v(std::istream_iterator<int> { infile }, std::istream_iterator<int> { } );
now v
contains numbers. if there's input error anywhere along way, won't see , input stop. if that's issue, utilize getline
/istringstream
approach, has been documented in hundreds of similar questions on site.
c++ arrays file-io io
Comments
Post a Comment