Reading a number from a text file using a C ++ stream

I have a text file as below

2 1 2
5 10 13 11 12 14
2 0 1
2 99 2
200 2
1 5
5 1 2 3 4 5
1 0
0 0

I want to read a file line by line and read lines from each line. I know how to use a stream to read a fixed line of a field, but what about an unfixed line?

Regards,

+3
source share
2 answers

Use a string stream. In the scheme:

string line;
while( getline( cin, line ) ) {  // read each line:
   istringstream is( line );
   int n;
   while( is >> n ) {   // read each number in line
       // do something with each number:
   }
}
+8
source

More efficient version, then getline + stringstream:


    vector<vector<int> > numbers;
    int num;
    for (;;) {
        if (file.peek() == '\n') {
            numbers.resize(numbers.size() + 1);
        } else if (!isspace(file.peek())) {
            if (!(file >> num)) break;
            numbers.back().push_back(num);
            continue;
        }
        file.get();
    }
+1
source

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


All Articles