cin.get() in a loop

戏子无情 提交于 2019-12-04 05:18:50

Mixing formatted and unformatted input is fraught with problems. In your particular case, this line:

std::cin >> n;

consumes the number you typed, but leaves the '\n' in the input stream.

Subsequently, this line:

cin.get (a, 10);

consumes no data (because the input stream is still pointing at '\n'). The next invocation also consumes no data for the same reasons, and so on.

The question then becomes, "How do I consume the '\n'?" There are a couple of ways:

You can read one character and throw it away:

cin.get();

You could read one whole line, regardless of length:

std::getline(std::cin, some_string_variable);

You could ignore the rest of the current line:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

As a bit of related advice, I'd never use std::istream::get(char*, streamsize). I would always prefer: std::getline(std::istream&, std::string&).

Adding a cin.get() before cin.get(a, 10) will solve your problem because it will read the remaining endline in the input stream.

I think it is important to know this when you are using cin : http://www.cplusplus.com/forum/articles/6046/

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!