Why is a second cin.ignore() necessary?

前端 未结 2 2000
清酒与你
清酒与你 2021-01-06 01:37

I\'ve noticed that whenever I write a program that uses std::cin that if I want the user to press Enter to end the program, I have to write std::cin.ignor

相关标签:
2条回答
  • 2021-01-06 02:13

    That's strange. What platform are you running on? By definition, ignore extracts and discards n characters from the input stream or if it hits EOF it stops. If you do not specify any parameters it extracts 1 character. On Windows, line ending involves both a \r and a \n -- a total of two characters (a carriage return followed by a newline).

    0 讨论(0)
  • 2021-01-06 02:23

    Discl: I'm simplifying what really happens.

    The first serves to purge what the extraction operator (>>) hasn't consumed. The second waits for another \n.

    It is exactly the same when we do a std::getline after an extraction: a the_stream::ignore(std::numeric_limits<streamsize>::max(), '\n'); is required before the call to std::getline()

    0 讨论(0)
提交回复
热议问题