reading from a data file

Mar 15, 2008 at 12:38am
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.
Mar 15, 2008 at 11:10pm
Mar 16, 2008 at 4:25pm
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.
Mar 16, 2008 at 5:56pm
That sounds complicated. Normally you can read floating point number directly from the file:

1
2
3
ifstream is(file);
float f;
is >> f;
Mar 16, 2008 at 7:46pm
You could also read the file byte-wise and check if the character is a letter or a digit and proceed accordingly.
Mar 16, 2008 at 10:15pm
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 Mar 16, 2008 at 11:03pm
Topic archived. No new replies allowed.