getchar是读入函数的一种。它从标准输入里读取下一个字符,相当于getc(stdin)。返回类型为int型,为用户输入的ASCII码或EOF(EOF是文件结尾标志).
一个常见的应用是以这个函数为结尾,以防止窗口的闪退(不用system("pause"))
getchar有一个int型的返回值。当程序调用getchar时.程序就等着用户按键。用户输入的字符被存放在键盘缓冲区中。直到用户按回车为止(回车字符也放在缓冲区中)。当用户键入回车之后,getchar才开始从stdio流中每次读入一个字符。getchar函数的返回值是用户输入的字符的ASCII码,若文件结尾(End-Of-File)则返回-1(EOF),且将用户输入的字符回显到屏幕。如用户在按回车之前输入了不止一个字符,其他字符会保留在键盘缓存区中,等待后续getchar调用读取。也就是说,后续的getchar调用不会等待用户按键,而直接读取缓冲区中的字符,直到缓冲区中的字符读完后,才等待用户按键。
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
char ch,c,h;
ch=getchar();
cout<<ch<<endl;
c=getchar();//后续
cout<<c<<endl;
h=getchar();//后续
cout<<h<<endl;
return 0;
}
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
char ch;
ch=getchar();
cout<<ch;
return 0;
}
缺点:经常只使用一次的getchar()函数只记录字符串(多输入)换行符前的第一个字符,记录n个则需执行n次.getchar()只读取一个字符与其说是他的缺点,不如说是他的特点,因为多输入用cin/scanf读取字符串就行了.
让我们来读取跨行的字符试试:
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
char c[5];
for(int i=0;i<=5;i++)
{
c[i]=getchar();
}
cout<<"输出字符组成的字符串为:";
cout<<c;
return 0;
}
从输出结果就可以看出:读入字符中包含了三个我们不经意输入的换行符.
解决办法
#include <cstdio>
#include <iostream>
using namespace std;
char readchar(){
char ch;
for(;;){
ch=getchar();
if(ch != '\n' && ch != '\r')
return ch;
}
}
int main()
{
char c[5];
for(int i=0;i<=5;i++)
{
c[i]=readchar();
}
cout<<"输出字符组成的字符串为:";
cout<<c;
return 0;
}