Reading lines of different sizes?

data.txt

1 2 7 4 123 5 6
2 1 1.5
3 2 50 4 50.2
4
5 2 10.5 3 13.9


My code:
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
31
32
33
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>

using namespace std; 

int main(int argc, char **argv) {
 ifstream file(data.txt);
 string data;
 vector<string> theData;

 if (!file) {
    cout << "Could not open file." << endl;
    exit(1);
 }

 while(file >> data) {
 	if (data == '\n') {
 		for (int i = 0; i < theData.size(); i++) {
 			cout << theData[i] << " ";
 		}
 		cout << "------------" << endl;
 		theData.clear();
 		continue;
 	}
 	theData.push_back(data);
 }

 file.close();

 return 0;
}


My intended output is:
1 2 7 4 123 5 6
-------------
2 1 1.5
-------------
3 2 50 4 50.2
-------------
4
-------------
5 2 10.5 3 13.9
-------------


I know that the problem is at " if (data == '\n') " but how can I resolve this? I want to treat each individual integer of each line as a separate entity (so I can use the vector for some other methods and then I'll clear it for the next line). Each line size varies.
Last edited on
If you are interested in the contents of each line, read a whole line at a time.
Then use a stringstream to parse the contents of the line.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>

int main()
{
    std::ifstream file("data.txt");
    std::string line;
    
    while (getline(file, line))
    {
        std::istringstream ss(line);
        double num;
        while (ss >> num)
            std::cout << std::setw(6) << num;
        std::cout << '\n';
    }   
}

Output:
     1     2     7     4   123     5     6
     2     1   1.5
     3     2    50     4  50.2
     4
     5     2  10.5     3  13.9
Topic archived. No new replies allowed.