cin>>problem again :)

Well in my last massage I asked for help and Duoas really kindly helped me :) and I know that for strings i should use getline(cin,stringname)

Now I have another question which is similar to my last one.
Ok so when I use cin>>var ; happens the same problem as in my last post.(http://www.cplusplus.com/forum/beginner/14100/) the problem is that this time it's not a string but a float number. So I searched a little bit and found out that 'cin' is leaving a newline on the input stream. Which leads to skipping the next cin. In that forum they suggested using:

fflush(stdin)
after the cin but I made a little search on google on about it and found an article that we shouldn't use it. My question is should I trust that article and is there another way to fix that problem?

My program works fine with fflush(stdin) so I will use it for the future if some of the experts here don't give me a reason not to. Thanks for your answers.
Try putting
std::cin.ignore(std::numeric_limits <std::streamsize>::max, '\n');
after your cin statement.
so this is a better practice that fflush(stdin) ?
Yes, that is a better practice then fflush(stdin).
It will not lead to the skipping of the next cin. Only the skipping of the next getline(). To counter this problem of getlines and cin coexisting in the program just place a cin.ignore() after every cin input statement.
No.
I would not have written
std::cin.ignore(std::numeric_limits<std::streamsize>::max, '\n'); if I was recommending him to write cin.ignore(); instead, would I?

So put that, not "just" cin.ignore();
Also you will need to #include <limits>
Last edited on
chrisname or someone else can you please explain why using
cin.ignore(numeric_limits<streamsize>::max,'\n'); is better?
If you leave it out, then some characters may still be left on the stream when you take input again. The way I showed you will ignore all characters on the stream (unless there are more characters on the stream than the maximum amount, which doesn't make sense), and therefore no matter how many characters cin leaves on the stream, your next cin will not be affected.

The other way, without std::numeric_limits<std::streamsize>::max, will only ignore enter key presses. The way above ignores both. At least, I think so.

Also take a look at this:
http://www.cis.nctu.edu.tw/chinese/doc/research/c++/C++FAQ-English/input-output.html#faq-15.2
Last edited on
Last edited on
Topic archived. No new replies allowed.