C++字符串输入输出操作详解
还有一个常用的 getline() 函数,该函数的原型包括两种形式:
template <class CharType, class Traits, class Allocator > basic_istream<CharType, Traits>& getline (basic_istream<CharType, Traits>& _Istr,basic_string <CharType,Traits, Allocator> &_Str);
//上述原型包含 2 个参数:第 1 个参数是输入流;第 2 个参数是保存输入内容的字符串
template <class CharType, class Traits, class Allocator> basic_istream<CharType, Traits>& getline (basic_istream <CharType, Traits>&_ Istr, basic_string <CharType, Traits, Allocator>& _Str,CharType_Delim);
//上述原型包含 3 个参数:第 1 个参数是输入流,第 2 个参数保存输入的字符串,第 3 个参数指定分界符。
下面分别按上述两种函数原型举例说明,参见下述程序:
#include <iostream> #include <string> using namespace std; void main () { string s1, s2; getline(cin, s1); getline(cin, s2, ' '); cout << "You inputed chars are: " << s1 << endl; cout << "You inputed chars are: " << s2 << endl; }程序的执行结果为:
123456
asdfgh klj
You inputed chars are: 123456
You inputed chars are: asdfgh