I have this class structure, I'm trying to read in strings.
for (int count = 0; count %26lt; num; count++) {
cfile %26gt;%26gt; library[count].name.last;
cfile %26gt;%26gt; library[count].name.first;
getline(cfile, library[count].book.title);
cfile %26gt;%26gt; library[count].book.pages;
getline(cfile, library[count].book.genre);
getline(cfile, library[count].book.other.publisher);
cfile %26gt;%26gt; library[count].book.other.year;
}
And I asked this guy and he said:
After you cin%26gt;%26gt; name.first and name.last, you will have read "Jk" and "Rowling", respectively, but you've left the newline in the stream. The call to getline will receive an empty line, and when you try to convert that empty string to a number, you get something completely random like 211400.
How do I get rid of the newline character, something to do with cin.ignore????
How do I get rid of the newline character in C++ using ignore?
The guy you asked answered correctly. When reading from an instream object using %26gt;%26gt;, you have to be careful about newlines being left behind.
I could type up the solution here, but someone else has already done so. I'll give you the link: http://www.daniweb.com/tutorials/tutoria...
I'll summarize the two solutions you have. The first, and recommended for beginners to C++, is to avoid cin and use getline instead. The other way is cin.ignore(numeric_limits%26lt;streamsize%26gt;::m... '\n').
Please read the entire article. It is technically accurate as well.
In the future, use Google to find out answers. There's good resources at "C++ FAQ", cplusplus.com , cppreference.com.
Reply:cin.ignore('\n');
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment