Reading a file using c++ need a little help in reading columns

DAWeinG

Platinum Member
Aug 2, 2001
2,839
1
0
My friend needs help reading the rows of a file:

The file looks like this:

L D Q
------------------------------
34 2 1
45 3 2
23 1.5 0

I need the program to READ the separate doubles there and store them each into a variable, (ie. x = 34, y = 2, z = 1); Each three numbers of a row at a time.

Suggestions? TIA
 

notfred

Lifer
Feb 12, 2001
38,241
4
0
I haven't worked in C++ for a while, but it's something like:

int array[50];

for(int i = 0; i <50; i++){


aw, hell, I can't remember.

in perl you can do this:

open (FILEHANDLE, "filename");
@array_of_lines = <FILEHANDLE>

foreach $line(@array_of_lines){
@numbers = split /\s/, $line;

#do whatever you need with $numbers[0], $numbers[1], $numbers[2]

}
 

bUnMaNGo

Senior member
Feb 9, 2000
964
0
0
is it *always* going to have the first two lines, then having three doubles per line? without error checking, you can do something like:

inFile >> a >> c >> d; // assuming x, y, z are chars
inFile.getline();
while(inFile >> x >> y >> z){
// do whatever you want with x, y, and z here
}

you might have to fumble around with the getline to get rid of the \n at the end of the first two lines. but this is pretty much it.
 

DAWeinG

Platinum Member
Aug 2, 2001
2,839
1
0
Hmm ya there two lines are always going to be there :( How can I skip those two lines? Is there a command which allows me to do that?
 

Platypus

Lifer
Apr 26, 2001
31,046
321
136
you want to use a getline. Why don't you store the entire line as a variable and then make a function that seperates the numbers into smaller variables using spaces etc.

Ex: 34, 2, 1 = variable 1

Then run variable 1 through your function and seperate each one into seperate variables.
It may seem like a lot of work, but if you have a lot of those lines, making two loops is a lot easier then doing it with arrays.
 

bUnMaNGo

Senior member
Feb 9, 2000
964
0
0
err the first two lines of my code should do it... read in the first three characters, then just getline the next line... as I said the getline might grab the '\n' from the first line, so you might another getline to get the 2nd. let me know if it works.