input file help

I have an input file that I'm trying to input data from as int, string, and doubles. The data file is in the format:

John Doe
Best book ever
97.54
4 (aisle book is on)

Jane Doe
Greatest Book Ever
65.76
5

This is how I'm doing the input:

ifstream infile;
double price1, price2;
int aisle1, aisle2;
string name1, name2, title1, title2;

getline(infile, name1);
getline(infile, title1);
infile >> price1;
infile >> aisle1;
getline(infile, name2);
getline(infile, title2);
infile >> price2;
infile >> aisle2;

when I cout the variables, the second set of getlines doesn't work.

Why?


When you use the >> operator, it leaves the newline (\n) character in the input stream. If you use the >> operator again after this, it knows to ignore the \n character and get the intended input. However, if you use getline or get after >>, it does not know to ignore the \n character and will simply take that character and be done, never asking the user for input.

You can fix this in two easy ways. First, you could just use getline for everything and never use infile, or you can use infile.ignore() after infile >> and before getline (at least I'm pretty sure this works for files; I haven't done this in a while). What ignore() does is it just takes the first character in the stream and removes it, thus solving the problem described above.

Thanks for the reply. I tried the infile.ignore(); between the infile >> and getline and get the same thing, no chnages. I can't input int or double using getline, right? I get bugs when I use getline to obtain integers from the input file.
Oh right, duh, getline reads it all into a string. Instead of using ignore you could use getline or get to remove the \n character.
is there another way to input int or double using getline? I've been switching b/t getline and >> to input strings and ints/doubles, respectively, and the \n is what's throwing everything off.
Topic archived. No new replies allowed.