Need help with reading file

I need a little help on modifying my code to be able to read a file with bad data and without a terminator in the file.

This is the file i need to read:

Mickey Mouse S45 78Y W91 -1
Minnie Mouse HH95DF E92DD P88D -1
Jack Robinson -1
Jimmy Johnson SSF54S W89W U66T DD44S DD21S -1
Donald Duck WQ72Q A81B EE89W -1

"-1" is the terminator, but i'd like to read the file without having to use the "-1." I know i have to use something like "num=in.get();" but Im not quite sure how to do it, any help would be appreicated.

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
34
int main()
{
	int num = int();
	string fname = string();
	string lname = string();

	ifstream in;
	in.open("test.txt");

	while (!in.eof())
	{
		in >> fname >> lname;
		cout << fname << " " << lname << " ";
		while (num >= 0)
		{

			in >> num;
			if (in.fail())
			{
				in.clear();
				in.ignore(1,'\n');
			}
			else
			{
				if (num >= 0)
				{
					cout << num << " ";
				}
			}
		}
		
		num = 0;
		cout << endl;
	}
A couple of general comments, it's not a good idea to use eof() in a while loop condition, its generally something to be avoided. Secondly, you don't need to put string fname = string();, it's sufficient to put string fname; and an empty string will be properly initialised. In the case of int num = int(); it would be better to put either int num = 0; or int num(0); if you need to assign an initial value.

As for reading this file, I'd suggest reading each line using getline(), and then read the contents of that line as though it was a file, by using a stringstream. Possibly something like this:
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
34
35
36
37
38
39
40
41
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

    using namespace std;

int main()
{
    int num;
    string fname;
    string lname;

    ifstream in("test.txt");
    string line;
    
    while (getline(in, line))
    {
        istringstream ss(line);
        
        ss >> fname >> lname;
        cout << fname << " " << lname << " ";
        
        while (ss)
        {
            if (ss >> num)
            {
                cout << num << " ";
            }
            else
            {
                ss.clear();
                ss.get(); // ignore one character
            }
        }
        
        cout << endl;
    }
    
    return 0;
}  
Thanks for the help, had to read what stringstream was since I hadn't learned that yet, you learn something new in programming everyday.
Topic archived. No new replies allowed.