我用C++编写了这段代码,并使用getchar()
来创建控制台,但我没有看到使用该函数的任何效果,以下是代码:
#include<iostream>
#include<stdio.h>//to pause console screen
using namespace std;
//function prototypes
int getSmallest(int*);
int getOccurrence(int, int*);
int main(){
int a[7], counter=0, smallest;
cout<<"Please enter 7 integers"<<endl;
while(counter!=7){
cin>>a[counter];
counter++;
}
smallest=getSmallest(a);
cout<<"The smallest number is "<<smallest<<"; it apears "<<getOccurrence(smallest,a)<<" times"<<endl;
getchar();//to pause console screen
return 0;
}
int getSmallest(int*x){
int count=0, smallest=*x;
//loop till last item in array
while(count!=7){
if(*x<smallest)
smallest=*x;
count++;
x++;
}
return smallest;
}
int getOccurrence(int smallest, int* address){
int count=0,occ=0;
//loop till last item in array
while(count!=7){
if(*address==smallest)
occ++;
count++;
address++;
}
return occ;
}
发布于 2011-12-09 16:53:49
如前所述,问题在于您的输入缓冲区有一个数字字符串和一个换行符。当C++ I/O读取类似数字输出的内容时,它会跳过前导空格,但不会将尾随空格从缓冲区中取出。它将这个问题留给下一次阅读来处理。所以getchar()
得到了新的行号,它还在等待处理。
忽略那些试图告诉您刷新()、忽略()或清除“在getchar()
调用之前缓冲区中的任何内容”的人的建议。这些函数没有“非阻塞”输入的概念。
换一种说法:通常的C++输入流函数没有“现在什么都没有”的概念,然后你稍后调用它,它会说“哦,...but now there's then!”有一个“输入序列”,当你点击EOF时,你只能检测到它停止了。
例外情况是readsome()...which,而不是在“输入序列”上操作,而是在“输入缓冲区”上操作。找到这样的东西,我们可以尝试这样做:
#include<iostream>
#include<cstdio>//to pause console screen
using namespace std;
int main(int argc, char* argv[]) {
cout << "Enter a number\n";
int num;
cin >> num;
char ch;
while (cin.readsome(&ch, 1) != 0)
;
cout << "Press any key to continue...\n";
getchar();
return 0;
}
但至少在我的机器上,它不会产生预期的效果。这意味着即使在终端应用程序或操作系统管道中的某处有一个换行符,它也还没有达到cin
的内部流缓冲区对象。结果是:有一个基于缓冲区的非阻塞输入函数,但在这种情况下,它显然不会有帮助。
真正的答案是Alf在评论中说的话。大多数像样的开发环境或设置都会有一些方法将其配置为不让控制台自动关闭。如果没有,就用你的启动方法绕过它。见鬼,你甚至可以在main中的return 0
上设置断点!
备注:
您应该知道,C兼容性库的“正确”C++包含是作为#include <cfoo>
而不是#include "foo.h"
完成的。这可能不会对practice...but产生太大的影响,至少当人们对它发表评论时,它会分散人们对你的问题的注意力(就像我现在正在做的那样):
此外,您可以用一个小得多的示例来演示这一点!您可以简单地使用以下命令来显示效果:
#include<iostream>
#include<cstdio>//to pause console screen
using namespace std;
int main(int argc, char* argv[]) {
cout << "Enter a number\n";
int num;
cin >> num;
cout << "Press any key to continue...\n";
getchar();
return 0;
}
所以,试着减少你的例子,以便在将来真正隔离问题!(你可以随意修改你的问题,使其简明扼要,以便让这个帖子对人们搜索更有用。)
发布于 2011-12-09 16:12:49
试试这个:
int main()
{
// ...
std::cin.get();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return 0;
}
发布于 2011-12-09 16:08:58
这可能是缓冲区的问题。由于使用了buffer,getChar从buffer获取输入,因此在调用getChar()之前最好使用flush buffer
https://stackoverflow.com/questions/8442644
复制相似问题