高手指教一下,getchar()的问题

筋斗云王 2008-03-02 05:29:48
#include<iostream>
using namespace std;
int main()
{
cout<<"please input two numbers"<<endl;
int num1,num2,max,min,count=0;
//输出num1,num2
cout<<"before input current num is:"<<num1<<" "<<num2<<endl;
cin>>num1>>num2;

cout<<"after input current num is:"<<num1<<" "<<num2<<endl;

getchar();//暂停一下(如果输入的不是两个规范数,比如说是字母,在这里不会停顿

//判断输入的两个数的大小
if(num1>=num2)
{
max=num1;
min=num2;
}
else
{
max=num2;
min=num1;
}
//按每行不超过十个数来输出给定的两个数之间的数
for(int i=min;i<=max;i++,count++)
{
if(count!=0&&count%10==0)
{
cout<<endl;
count=0;
}
cout<<i<<" ";

}
getchar();
return 0;
}
...全文
108 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Michael_555 2008-03-02
  • 打赏
  • 举报
回复
运行一下这段代码,你就知道原因了

#include <iostream>
using namespace std;
int main()
{
int num = 0;
char ch;

cout<<"input a number num="<<endl;
cin>>num;

ch = getchar();
cout<<"inputed number is"<<num<<endl;
cout<<"input character is"<<ch<<endl;

return 0;
}


在显示input a number num=的时候输入
a
就会自动输出,不会对num做输入的
0, a
Michael_555 2008-03-02
  • 打赏
  • 举报
回复
如果你输入的不是数字,例如输入了英文字符,
cin> > num1> > num2不会从输入缓冲里面将输入的内容取出来的。
这样getchar()的时候,看到输入缓冲里面还有内容,就会直接取出一个字符,而不会停下来等待输入了。


HelloDan 2008-03-02
  • 打赏
  • 举报
回复

#include <iostream>
using namespace std;
int main()
{
cout <<"please input two numbers" <<endl;
int num1,num2,max,min,count=0;
//输出num1,num2
cout <<"before input current num is:" <<num1 <<" " <<num2 <<endl;
cin>> num1>> num2;

cout <<"after input current num is:" <<num1 <<" " <<num2 <<endl;

fflush(stdin);
getchar();//暂停一下(如果输入的不是两个规范数,比如说是字母,在这里不会停顿)

//判断输入的两个数的大小
if(num1>=num2)
{
max=num1;
min=num2;
}
else
{
max=num2;
min=num1;
}
//按每行不超过十个数来输出给定的两个数之间的数
for(int i=min;i <=max;i++,count++)
{
if(count!=0&&count%10==0)
{
cout <<endl;
count=0;
}
cout <<i <<" ";

}
getchar();
return 0;
}


int getchar ( void );



<cstdio>

Get character from stdin

Returns the next character from the standard input (stdin).
It is equivalent to getc with stdin as its argument.

Return Value
The character read is returned as an int value.
If the End Of File is reached or a reading error happens, the function returns EOF and the corresponding error or eof indicator is set. You can use either ferror or feof to determine whether an error happened or the End-Of-File was reached.

64,849

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧