getchar与cin混淆 [英] getchar confuses with cin(s)
本文介绍了getchar与cin混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通常我们将一个getchar放在一个控制台应用程序的末尾,作为关闭程序的命令。
但是getchar混淆了cin命令我猜有时候我不得不放一个以上的getchar在计划结束时。比如下面,
我该如何解决? (我的意思是我该怎么办才能在最后只有一个getchar?)
Usually we put a getchar at the end of a console application as a command to close the program.
But getchar confuse with cin orders i guess and sometimes i have to put more than just one getchar at the end of the program. such as below,
how should i fix it? (I mean what should i do to have only one getchar at the end?)
int main(){
vector<int> numbers(0);
cout << "please enter you numbers :::\n''entering any characters but numbers is the end of entry''\n";
int counter = 0;
do{
int newnumber = 0;
cout << "element(" << counter << ") = ";
counter++;
cin >> newnumber;
numbers.push_back(newnumber);
if (cin.fail()){
cout << "entered numbers are:\n";
for (vector<int>::iterator i = numbers.begin(); i != numbers.end(); i++)
{
cout << *i;
if (i != numbers.end()-1)cout << " - ";
}
}
} while (cin.good());
// here
getchar(); getchar(); getchar();
}
推荐答案
问题是输入缓冲区中可能已经存在某些字符。
根据许多缓冲输入,你需要更多的getchar。
一个简单的解决方案就是循环,同时''\\ n''被事先调用,也可以缓冲:
The problem is that some characters may already be present in the input buffer.
Depending on many buffered inputs are there you need more getchar.
A simple solution is to loop while a '\n' is ecountered de facto empting also the buffer:
int c;
do
c=getchar();
while (c!=EOF && c!='\n');
另一个非常经典的解决方案(来自DOS时代,但仍然有效)是:
Another really classic solution (coming from DOS times, but still working) is:
while(_kbhit())
_getch();
使用后一种解决方案,你不需要在流缓冲区中有一个'\ n'。
With the latter solution you don't need to have a '\n' in the stream buffer.
使用 cin.get()
而不是。
我忘了MS允许在输入流上使用fflush(),所以这个简单的行应该这样做:
I forgot that MS allows the use of fflush() also on input streams, so this simple line should do:
fflush(stdin);
这篇关于getchar与cin混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文