开发者

How can I clear the input stream in c++?

When I write a program, and use the -

cout << "A:"; 
cin >> string_var; 
cout << "B"; 
cin >> string_var2; 

If there is a space in between the two inputs on the keyboard (for ex. If the console displayed:

A:_ (waiting for input) and I typed 开发者_Python百科a a, the first a would go to the string_var and the second would go to string_var2. How can I flush the input stream?


Instead of cin >> string_var, use cin.getline(string_var, 256, '\n'). Your current method of reading input only reads up till the first space. Using the getline method will read up to the \n character which is when the user hits enter.


You can use cin.get() like this:

cout << "A: "; 
cin >> string_var; 
// clear remaining stream input
while(cin.get() != '\n'); 

cout << "B: "; 
cin >> string_var2;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜