本文共 1995 字,大约阅读时间需要 6 分钟。
C++标准库提供了一组丰富的输入/输出功能。C++的I/O发生在流中,流是字节序列:
预定义的cin 是 iostream 类的一个实例。cin 对象附属到标准输入设备,通常是键盘;cin 与流提取运算符>>
结合使用。
>>
cin默认使用空白(空格、制表符、换行符)来确定字符串的结束位置:
#includeusing namespace std;void testInput(){ int nAge; double height; string name; cout<<"Input Age, height, name: "; // 12 1.65 mike josn cin>>nAge>>height>>name; cout<<"Age: "< <<", Height: "< <<", Name: "< <
读取name时,只读取前面一部分(因空格结束了字符串的读取)。
cin.get()可以读取每个字符返回,也可把读取的内容放到字符参数中:
int_type get();basic_istream& get (char_type& c);
cin.get()依次读取每一个字符,直到结束(Ctrl+z):
void testGet(){ cout<<"Input: "; int nGet; while( (nGet=cin.get())!=EOF){ // 输入回车时,才依次读取(回车符本身也作为一个字符读取到 cout<<(int)nGet<
std::getline可以读取一行放入string中,cin.get与cin.getline可以读取一行放入到字符数组中。
std::getline从输入流中读取字符到string中,直到遇到分隔符(默认\n
):
istream& getline (istream& is, string& str, char delim);istream& getline (istream& is, string& str);
若指定分隔符(如设为空格),可用于字符串分割:
#include#include using namespace std;void testLine(){ cout<<"Input: "; string strIn; std::getline(cin, strIn);// cout<
cin.getline从输入流中读取字符到字符数组,直到遇到分隔符(默认\n
)或数组最大长度-1;末尾会自动添加NULL;通过gcount可获取读取字符数(包括分隔符):
basic_istream& getline (char_type* s, streamsize n );basic_istream& getline (char_type* s, streamsize n, char_type delim);
字符数组中不包含分隔符(且已从输入缓冲区中删掉了),但gcount包括分隔符(即:len(ary)+1):
char strIn[1024]; for(int i=0; i<5; ++i) { cin.getline(strIn, 1024); cout << "count: " << cin.gcount() << endl; }
cin.get从输入流中读取字符到字符数组,直到遇到分隔符(默认\n
)或数组最大长度-1;末尾会自动添加NULL:
basic_istream& get (char_type* s, streamsize n);basic_istream& get (char_type* s, streamsize n, char_type delim);
cin.get读取时,会把分隔符留在缓冲区中,若不主动去掉,则会一直读取空字符串:
char strIn[1024]; for(int i=0; i<5; ++i) { cin.get(strIn, 1024).get(); }
若没有后面的get(),则在读取一行后,后续一直读取空(因换行符还在缓冲区中)。
转载地址:http://kzilf.baihongyu.com/