reading from a data file

I need to know how to read strings and numbers from the same file. The strings are two word names and the numbers are heights.
I figured it out. I read the names using a getline and then used the get command to read in the numbers into a character array. Then I used the atof function to convert to a floating point. I also had to use an additional getline after the get statement to clear the new line character from the file.
That sounds complicated. Normally you can read floating point number directly from the file:

1
2
3
ifstream is(file);
float f;
is >> f;
You could also read the file byte-wise and check if the character is a letter or a digit and proceed accordingly.
Reading strings from a file is easy as is reading numbers. It gets complicated when you try to read both. After you read in a number, I found out that you have to clear the newline character after the number. I did it with a getline.

infile.open("Name_height.dat",ios::in);

getline(infile,l_name); //gets the first name

while(!infile.eof())
{

infile>>h;

cout <<l_name<<'\t'<<h<<endl;

getline(infile,nl); // removes the new line character from the file stream

getline(infile,l_name); // gets all the other names
}
Last edited on
Topic archived. No new replies allowed.