cin>>char
用cin>>char读入字符,例如一下代码段:
#include<iostream>
using namespace std;
int main(void)
{
char ch;
int count=0;
cout<<"输入字符串;以#作为结束标注\n";
cin>>ch;
while(ch!='#'){
cout<<ch;
count++;
cin>>ch;
}
cout<<endl<<count<<" 个字符被读入\n";
return 0;
}
输出结果:
结果显示用cin>>读入字符时,会自动跳过空格字符,将原本的11个字符串减去空格后变成10;
cin.get(char)
用cin.get(char)读入字符,例如一下代码段:
#include<iostream>
using namespace std;
int main(void)
{
char ch;
int count=0;
cout<<"输入字符串;以#作为结束标注\n";
cin.get(ch);
while(ch!='#'){
cout<<ch;
count++;
cin.get(ch);
}
cout<<endl<<count<<" 个字符被读入\n";
return 0;
}
输出结果:
结果显示用cin.get(char)读入字符时。不会跳过空格,同时不会读入换行符,。即Hello World中是11个字符,解决了cin>>会跳过空格的缺点。
以文件符EOF结束输入
可以用文件结束符EOF作为结束标志
EOF的输入
Linux系统:Ctrl+D
Windows/Dos系统:Ctrl+Z
当get函数读到EOF时,fail函数返回true。
因此可以利用cin.fail()==false作为结束标志。
这样就可以不断读入字符串,知道我输入Ctrl+z时即可结束程序循环。
例如一下代码段:
#include<iostream>
using namespace std;
int main(void)
{
char ch;
int count=0;
cout<<"输入字符串;\n";
cin.get(ch);
while(cin.fail()==false){
cout<<ch;
count++;
cin.get(ch);
}
cout<<endl<<count<<" 个字符被读入\n";
return 0;
}
输出结果:
结果显示读入的字符串当中包含了换行符'\n'。
因此用cin.fail()作为结束标志时,不仅可以读入任意字符,同时还可以读入换行符。功能强大。
总结
用cin>>char输入字符会自动跳过空格,而用cin.get(char)不会跳过空格,会把空格读进去(不读入换行符)。
而当我们需要不断读入字符时,同时字符可能是任意字符的情况下,我们就可以用文件结束符EOF作为输入结束标志。同时这种情况可以读入换行符,与前面的两种不同。
以后在写代码时应注意。