How to only read every 2nd line? Actually, look at this yourself...

Okay, here's whats inside myData.txt:

Natalie
1.000

John
2.000

Bob
3.000


I need to gather the total of ALL of those numbers. Here's what I got:
1
2
3
4
5
6
7
8
9
string name, data;
double sum( 0. );
ifstream in_stream( "myData.txt" );
while( getline(in_stream, name) ) // if you can get a name
{
	getline( in_stream, data); // then get the number!
	in_stream.ignore(1, '\n'); // ignore the new lines
	cout << data << endl; // output what you found
}
This outputs:

1.000
2.000
3.000

These are held as strings however, I have no clue how to cast these into doubles to add them all up. sum += static_cast<double>(data) doesn't work :(

Last edited on
double d_data;
...
d_data = atof(data.c_str());
I cant use atof, we didn't learn it yet so its unallowed. Well, this works perfect...need some help though:

1
2
3
4
5
6
7
8
9
10
11
12
string name, data;
double tempNum, sum( 0. ); 
while( getline(in_stream, name) )
{

	in_stream >> tempNum;
	sum += tempNum;
	in_stream.ignore( 1, '\n' );
	in_stream.ignore( 1, '\n' );
	
}		
cout << sum << endl; // Outputs 6, perfect. 
Is that the proper way to do it? I ignore the 2 new lines that that follows the number.

John\n
2.000\n <--- ignore
\n <--- ignore

Correct or no?
Last edited on
yeah that should work because getline would take in the newline byte.

i think you simplify it by changing it to in_stream.ignore( 2, '\n' );

and i think you should change your while loop statement so it stops at a newline byte.

So, getline(in_stream, name, '\n')
Topic archived. No new replies allowed.