Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在另一个输入请求c+之前清除cin缓冲区+;_C++_Input_Cin - Fatal编程技术网

C++ 在另一个输入请求c+之前清除cin缓冲区+;

C++ 在另一个输入请求c+之前清除cin缓冲区+;,c++,input,cin,C++,Input,Cin,我有以下代码: int choice = 0; char st1[N]; cout << "enter choice" <<endl; cin >> choice; cout << "enter sentence" << endl; cin.get(st1, N-1); int-choice=0; 字符st1[N]; 在cin>>选择之后,不能执行getchar()。这将消耗输入缓冲区中的\n 由于choice类型为int,因此\

我有以下代码:

int choice = 0;
char st1[N];

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

cout << "enter sentence" << endl;
cin.get(st1, N-1);
int-choice=0;
字符st1[N];
在
cin>>选择之后,不能执行
getchar()
。这将消耗输入缓冲区中的
\n

由于
choice
类型为
int
,因此
\n
留在缓冲区中,当字符串输入时,遇到该
\n
,它将停止在缓冲区中输入。

您可以使用从缓冲区中删除换行符(例如,在换行符之前删除X个字符作为分隔符)。提取分隔符时,提取和忽略停止

e、 g

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

同样相关:

您可以尝试使用
cin.sync()

我建议使用getline(cin,aString);这将不会在流中留下任何输入+它是类型安全的。这不会真正清除
cin
输入缓冲区。作为最后的手段,
cin.clear()
可以,包括重置所有流错误状态。这不会清除输入缓冲区,但会在OP的情况下完成作业。不能保证单个
getchar()
调用可以正确完成作业。这完全取决于用户在
cin>>选项中实际输入的内容!在这种情况下,其他解决方案也可能无法奏效。这完全是另一种情况。如果输入是s.th,会发生什么。这样:
3\n
?对于示例,我已经对您的答案投了赞成票。我只是想把这个和另一个“答案”对比一下。。。
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');