getchar()
只能输入一个字符型,且可以吃掉换行。
putchar()
只能输出一个字符型,且C和C++的标准输入流按回车后才会返回 ,如果流里没东西, 那就得回车才有反应, 如果已经有东西,就可以直接返回 .[系统的输入(读入到缓冲区)和输出函数(在屏幕上回显,所以你能看到输入的内容)这也是你在输入错字符时,可以按退格键删掉的原因,当你按下回车时,系统才允许你写的程序,从缓冲区里读数据,putchar()才能够输出,且可以一次将缓存的多个输出]
例:
#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std;
int input()
{
int ch;
while(1)
{
ch=getchar();
if(ch!='\n')
break;
}
return ch;
}
int main()
{
int ch;
int n=4;
while(n--)
{
ch=input();
putchar(ch);
}
}
此代码在一行输入asdf然后换行后会一次性输出asdf。
但是如果输入as然后换行会输出as,在输入d换行会输出d,在输入f换行会输出f。
putchar()只有在遇到换行或输入流截至时才输出。
‘\n’和’\r’的区别:
‘\r’就是”回到行首”,’\n’`就是”到下一行”
即:\r是回车,\n是换行,前者使光标到行首,后者使光标下移一格。
通常用的Enter是两个加起来的,即\r\n.
代码:
#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std;
int main()
{
cout<<"aaaa\rssss"<<endl;
cout<<"aaaa\nssss"<<endl;
cout<<"aaaa\r\nssss"<<endl;
}
输出为:
\r会用ssss将已经输出的aaaa替换,因为\r是回到当前行的行首。