cin.get();cin.clear();cin.sync()
先看代码:
#include<iostream> using namespace std; int main(){ int c,x; cout<<"输入大小"<<endl; cin>>c; x=c+1; cin.sync();//神器;用来清空输入缓冲区剩余的值的 char a[x]; cout<<"输入内容"<<endl;//因为输入大小后直接输入了回车,回车在缓冲区,没有被丢弃,所以a[]直接取的缓冲区的值;直接结束; cin.get(a,x);//cin.get的参数应该大1;多出一个填充回车; for(int i=0;i<c;i++){ cout<<a[i]<<endl; } cout<<sizeof(a)<<endl; return 0; }
当不用cin.sync()时,cin一个字符,用“回车”结束,但是cin不读入“回车”这个字符,所以回车会留在缓冲区,当cin.get()时,它首先读取缓冲区的内容;然后发现没有才会让你在屏幕输入,但是有内容它就会先读取,所以马上就结束了。
cin.get() this function can read "space" to the char array; Like this:cin.get(char*a,int b),"a" is the name of array,"b"is the number of read characters;
tips: because cin.get() also can accept "Enter" ,so we must made the "b" to be "+1" then the number you want.
cin.clear();的作用是清空错误的标志;并不是清空缓冲区的;详情请见:http://www.cnblogs.com/tonglingliangyong/p/3908463.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步