Counting lines and reading contents

I am trying to read the contents from a file, while counting the amount of lines of the same. The input would be something like this:

1
2
3
17 18 19 10
28 92 10
24 59 90 09


Although the actual file would contain lines long hundreds of characters, and could have hundreds of lines. I can already read the contents themselves, with the below method:

1
2
3
4
5
6
    int tileValue;

    while( levelDesign >> tileValue)
    {
        DesignVector[0].push_back( tileValue );
    }


But the above cannot detect newlines. I know how to count the lines themselves, but I need to know when they reach the newline, so I can access the next member of DesignVector, as above. Thanks for the help.
The usual approach is to read lines first, and then re-parse each line to read the contents:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
int main()
{
    std::ifstream tileValue("test.txt");
    std::vector< std::vector<int> > DesignVector;
    // outer loop: read line by line
    for(std::string line; getline(tileValue, line); )
    {
        std::vector<int> lineVector;
        std::istringstream buf(line);
        // inner loop: read the numbers from this line
        for(int tileValue; buf >> tileValue; )
        {
            lineVector.push_back(tileValue);
        }
        DesignVector.push_back(lineVector);
    }

    std::cout << "There were " << DesignVector.size() << " lines \n";
    for(size_t n = 0; n < DesignVector.size(); ++n)
    {
        for(size_t m = 0; m < DesignVector[n].size(); ++m)
           std::cout << DesignVector[n][m] << ' ';
        std::cout << '\n';
    }
}
Last edited on
Thank you for the help!
Topic archived. No new replies allowed.