How to read in space separated information from a file in C ++

In the text file, I will have a line containing a series of numbers, with each number separated by a space. How would I read each of these numbers and store them all in an array?

+3
source share
2 answers
std::ifstream file("filename");
std::vector<int> array;
int number;
while(file >> number) {
    array.push_back(number);
}
+6
source

Just copy them from the stream to the array:

#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    std::ifstream file("filename");
    std::vector<int> array;

    std::copy(  std::istream_iterator<int>(file),
                std::istream_iterator<int>(),
                std::back_inserter(array));
}
+5
source

Source: https://habr.com/ru/post/1738810/


All Articles