当前位置:嗨网首页>书籍在线阅读

20-输出和输入

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

F.8 输出和输入

string类重载了<<运算符来显示string对象,该运算符返回istream对象的引用,因此可以拼接输出:

string claim("The string class has many features.");
cout << claim << endl;

string类重载了>>运算符,使得能够将输入读入到字符串中:

string who;
cin >> who;

到达文件尾、读取字符串允许的最大字符数或遇到空白字符后,输入将终止(空白的定义取决于字符集以及charT表示的类型)。

有两个getline()函数,第一个的原型如下:

template<class charT, class traits, class Allocator>
basic_istream<charT,traits>& getline(basic_istream<charT,traits>& is,
            basic_string<charT,traits,Allocator>& str, charT delim);

这个函数将输入流is中的字符读入到字符串str中,直到遇到定界字符delim、到达文件尾或者到达字符串的最大长度。delim字符将被读取(从输入流中删除),但不被存储。第二个版本没有第三个参数,同时使用换行符(或其广义形式),而不是delim:

string str1, str2;
getline(cin, str1);      // read to end-of-line
getline(cin, str2, '.'); // read to period