先看下面两个程序:
程序1:
#include#includeusing namespace std;char a[100];char b[100];int main(){ cout<
运行结果:
程序2:
#include#includeusing namespace std;int main(){ string a,b; cout<
运行结果:
从上面两个程序我们可以看到:无论是使用字符数组还是string类型字符串变量,我们输入字符串时都是以回车结束。上述两个程序中的书写形式均可正常执行,第一个字符串输入结束时的回车不影响第二个字符串的输入。
我们再看下列两个程序,假设我们想输入的字符串是“abc”:
程序1:
#include#includeusing namespace std;char b[100];int main(){ int a; cout<>a; gets(b); cout<
int a的输入以回车结束时的运行结果:
int a的输入以空格结束时的运行结果:
程序2:
#include#includeusing namespace std;int main(){ int a; string b; cout<>a; getline(cin,b); cout<
int a的输入以回车结束时的运行结果:
int a的输入以空格结束时的运行结果:
由运行结果我们可以看到,此种情况下,无论int a的输入cin>>a以哪种形式结束输入,均会影响字符串b的输入。(以回车结束时无法输入字符串,以空格结束时字符串前多了一个空格)原因是cin是从输入缓冲区读入数据的,读取成功后分隔符回车和空格还留在输入缓冲区,后续使用gets()或getline()输入时会读取到它们。我们在写代码的过程中要注意此种情况。