标准输入流是从标准输入设备(键盘)流向程序的数据。在上一节中已知,在头文件iostream.h中定义了cin,cout,cerr,clog 4个流对象,cin是输入流,cout,cerr,clog是输出流。
cin是istream类的对象,它从标准输入设备(键盘)获取数据,程序中的变量通过流提取符“>>”从流中提取数据。流提取符“>>”从流中提取数据时通常跳过输入流中的空格、tab键、换行符等空白字符。
注意: 只有在输入完数据再按回车键后,该行数据才被送入键盘缓冲区,形成输入流,提取运算符“>>”才能从中提取数据。需要注意保证从流中读取数据能正常进行。
例.5 通过测试cin的真值,判断流对象是否处于正常状态。
- #include <iostream>
- using namespace std;
- int main( )
- {
- float grade;
- cout<<"enter grade:";
- while(cin>>grade)//能从cin流读取数据
- {
- if(grade>=85) cout<<grade<<"GOOD!"<<endl;
- if(grade<60) cout<<grade<<"fail!"<<endl;
- cout<<"enter grade:";
- }
- cout<<"The end."<<endl;
- return 0;
- }
运行情况如下:
在不同的C++系统下运行此程序,在最后的处理上有些不同。以上是在GCC环境下运行程序的结果,如果在VC++环境下运行此程序,在键入Ctrl+Z时,程序运行马上结束,不输出"The end."。
除了可以用cin输入标准类型的数据外,还可以用istream类流对象的一些成员函数,实现字符的输入。下面是几个常用的用于字符输入的流成员函数:
①用get函数读入一个字符
流成员函数get有种形式: 无参数的,有一个参数的,有个参数的。
- #include <iostream>
- int main( )
- {
- int c;
- cout<<"enter a sentence:"<<endl;
- while((c=cin.get())!=EOF)
- cout.put(c);
- return 0;
- }
运行情况如下:
- #include <iostream>
- int main( )
- {
- char c;
- cout<<"enter a sentence:"<<endl;
- while(cin.get(c)) //读取一个字符赋给字符变量c,如果读取成功,cin.get(c)为真
- {cout.put(c);}
- cout<<"end"<<endl;
- return 0;
- }
- #include <iostream>
- using namespace std;
- int main( )
- {
- char ch[20];
- cout<<"enter a sentence:"<<endl;
- cin.get(ch,10,'\\n');//指定换行符为终止字符
- cout<<ch<<endl;
- return 0;
- }
②用成员函数getline函数读入一行字符
getline函数的作用是从输入流中读取一行字符,其用法与带个参数的get函数类似。即
例.7 用getline函数读入一行字符。
- #include <iostream>
- using namespace std;
- int main( )
- {
- char ch[20];
- cout<<"enter a sentence:"<<endl;
- cin>>ch;
- cout<<"The string read with cin is:"<<ch<<endl;
- cin.getline(ch,20,'/');//读个字符或遇'/'结束
- cout<<"The second part is:"<<ch<<endl;
- cin.getline(ch,20); //读个字符或遇'/n'结束
- cout<<"The third part is:"<<ch<<endl;
- return 0;
- }
程序运行情况如下: