Reading numbers from .txt

Hello,
I have a text file like this
1
2
3
4
5
6
5
1 2 0
3 5 0
2 7 1
8 9 1
4 6 0


And the code is
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
	 ifstream infile;
	 infile.open("NongTrai.in.txt");
	 int in[4];
	 int N, x, y, l;
	 int file_limit = 0;
	 string line1, lines;
	 if (infile.is_open())
	 {
		 while (! infile.eof())
		 {			 
			 getline (infile, line1);
			 stringstream ss(line1);
			 ss >> N;
			 for (int i = 0; i < 4; i++)
			 {
				 getline (infile, lines);
				 stringstream ss;
				 ss >> lines;
				 lines = in[i];
			 }
			 x = in[0];
			 y = in[2];
			 l = in[4];
		 }
	 }
	 infile.close();


I'm trying to write a program to read the content. The first number will be read first and assigned to N. The following lines containing 3 numbers will be read and assigned to x, y, l respectively. But looks like I wrote the code wrongly. I haven't compile it since it's on my homework and I haven't finish the rest.
Can anyone help me with this?
Thank you!
Last edited on
Like so
1
2
3
4
5
6
7
8
9
10
11
12
if ( getline (infile, line1) ) {  // do we read the first line?
    stringstream ss(line1);
    if ( ss >> N ) {  // does it parse as an integer?
        for (int i = 0; i < N; i++) {
            if ( getline (infile, line1) ) {  // read N more lines
                stringstream ss(line1);
                if ( ss >> x >> y >> l ) {  // can we extract 3 integers?
                }
            }
        }
    }
}
Move the reading of N above the loop. You don't need stringstream. The loop may look like this:
1
2
3
4
5
6
7
8
	 if (infile.is_open())
	 {
		 infile >> N;
		 for (int i = 0; (i < N) && (infile >> x >> y >> l); i++)
		 {
			 ... // Note: you need to store x, y, l in an array
		 }
	 }
Since there're spaces between the numbers
 
1 2 0

Can I do like this to get only the numbers?
1
2
3
4
5
6
	for (int i = 0; (i < N) && (infile >> x >> y >> l); i++)
		{
			x = in[0];
			y = in[2];
			l = in[4];
		}
Since there're spaces between the numbers
white spaces are ignored. For what a white space is, see:

http://www.cplusplus.com/reference/cctype/isspace/

Can I do like this to get only the numbers?
Line 1 extracts the numbers only. Line 3 to 5 does not make sense.

If you want to use x/y/l later (after the loop) you still need to store the values into an array.
Topic archived. No new replies allowed.