在另一个输入请求之前清除cin缓冲区,c ++ [英] Clear the cin buffer before another input request, c++

查看:81
本文介绍了在另一个输入请求之前清除cin缓冲区,c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

int choice = 0;
char st1[N];

cout << "enter choice" <<endl;
cin >> choice;

cout << "enter sentence" << endl;
cin.get(st1, N-1);

到cin.get行时,无论输入是什么,它都将显示为\0将char转换为st1 [0]
就是这样。

when getting to cin.get line, no matter what the input is, it will read \0 char into st1[0] and that's it.

我认为它与最新的cin有关(到选择变量中)。

I assume it has something to do with the latest cin ( into choice variable ).

我如何在从用户那里获得新输入之前清洗 cin缓冲器?

How do i "clean" cin buffer before getting new input from the user? if that's possible.

谢谢

推荐答案

您可以使用忽略以便从缓冲区中删除换行符(例如,将X字符删除为换行符定界符)。

You might use ignore to drop the newline from the buffer (e.g. drop X characters before the newline as delimiter). Extraction and ignore stop when the delimiter is extracted.

例如

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

也相关:

Also related: Why would we call cin.clear() and cin.ignore() after reading input?

这篇关于在另一个输入请求之前清除cin缓冲区,c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆