cin >> //可连续使用;以空白(包括空格、回车、TAB)为分隔符
注:若读入失败,此时cin状态被修改为false,将不再进行读操作。因此若想继续读入,应该调用cin.clear()和cin.ignore()函数,前者把cin状态置为ture,后者清空输入流因为读入失败(如类型不匹配)留在流中的字符。
cin.get(char c) //可连续使用;获取任意单个字符,包括空白
cin.getline(char* buf, sizeof(buf), '\n') //可连续使用;获取一行,到最后指定的字符结束,可包括空白,默认回车
cin.gcount() //计数
cin.read(char* buf, sizeof(buf)) //可连续使用;读取指定大小的内容,包括空白;第一个参数必须为char*,可用强制转换
cin.ignore(1000, '\n') //忽略指定大小的内容,到制定字符结束忽略;常用来清空缓冲区
cin.clear() //清楚错误状态;常后跟ignore
if(!cin) //判断是否出错;cin为false则出错
cin.peek() //查看缓冲区下一个字符,但是不读取,即用get时候还可以读到
cin.putback() //将上一个读回的字符返回缓冲区,不常用
cout <<
控制符:endl, flush ....
cout.put(char)
cout.width(int) //一次性命令
cout.fill(char)
cout.precision(int)
cout.setf(ios::...)
cout.unsetf(ios::...)
(cout这些命令不常用,常用头文件中的函数代替)
程序分析
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int i=5, j;
while(i-- > 0){
cin>>j; //如果在dos输入非法字符,cin被置为失败状态,且非法字符仍然停留在缓冲区中,因此将使程序陷入死 循环。
cout<<j<<endl;
}
return 0;
}
修正程序:
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int i=5,j;
while(i-- > 0){
if (cin>>j)
{
cout<<j<<endl;
}
else
{
cin.clear(); //清楚失败状态
cin.ignore(1); //清空缓冲区(两个语句缺一不可)
}
}
return 0;
}
通常为了避免出现意想不到的死循环,程序往往写成
while(cin>>a){cout<<a<<endl;} //把读入成功与否放到循环中作条件
联系客服