一.
通常,IDE允许在辅助窗口中运行程序。程序执行完毕之后,有些IDE将关闭窗口,而有些不关闭,如果编译器关闭窗口,将很难看到程序输出,为了查看输出必须在程序的最后加上
cin.get();//add this statement
cin.get();//and maybe this, too
return 0;
cin.get()语句读取下一次键击,因此上述语句让程序等待,知道按下Enter键,(在按下Enter键之前,键击将不会被发送给程序,因此按其他键将不管用)。如果程序在其常规输入后留下一个没有被处理的键击那么第二条语句必须得有。
如果需要输入一个数字,那么输入这个数字按下Enter程序将读取这个数字,不会理睬这个Enter,这样,这个数字将会被第一个cin.get()
读取
二.
先看第一个程序:
Enter the name:
#include <iostream>
using namespace std;
int main()
{
const int size=20;
char name[size];
char add[size];
cout<<"enter name:"<<endl;
cin>>name;
cout<<"enter address:"<<endl;
cin>>add;
cout<<"your name is "<<name<<" and your address is "<<add<<endl;
return 0;
}
然后:
结果:
程序里面有两个cin,我输入的空格把正是第一个cin结束的标志,如果我想让这里面的name:后面是Asuka Shin,那么就需要cin.get()这条语句了。
so
#include <iostream>
using namespace std;
int main()
{
const int size=20;
char name[size];
char add[size];
cout<<"enter name:"<<endl;
cin.get(name,size);
cout<<"enter address:"<<endl;
cin.get(add,size);
cout<<"your name is "<<name<<" and your address is "<<add<<endl;
return 0;
}
这样的话,结果就是:
解释原因:
当用cin输入的时候,例如输入100,当键盘按过回车键的一瞬间,一个\n出现在键盘缓冲区;
也就是说,当cin>>读取输入的数据的时候,他遇见 \n 就结束了而且 \n 没有被读取,还在键盘缓冲区。
而cin.get()函数执行的时候,他先从先前输入操作停止的键盘缓冲区读取,而且遇到了\n
但cin.get(name,size);读取到行尾后丢弃换行符,因此读取一次后换行符任留在输入队列中
但这还不是我想要的
因为不管再怎么输入,address后面还是什么都没有;
So
#include <iostream>
using namespace std;
int main()
{
const int size=20;
char name[size];
char add[size];
cout<<"enter name:"<<endl;
cin.get(name,size);
cin.get();
cout<<"enter address:"<<endl;
cin.get(add,size);
cout<<"your name is "<<name<<" and your address is "<<add<<endl;
return 0;
}
结果是:
这正是我想要的。
在cin.get(name,size);
后面加一条语句:
cin.get();//读取回车键
该函数可以读取一个字符,将换行符读入。
当然也可以将他们拼起来:cin.get(name,size).get()//简单暴力Ncie;
总之一句话:cin.get(name,size).get()解决所有不服。
C语言中
scanf("%s %c",数组名,&变量名)//字符串
这个遇到空格就结束,相当于C++里面的cin;
之后
gets(数组名)//可以输入空字符 相当于cin.get(name,size).get()。
a = getchar()//输入单个字符