在学习C/C++的时候,对于输入部分的相关知识一直没有真正的搞清楚,与其一直浑浑噩噩,不如专门花个时间搞清楚它们。
string::getline()
istream& getline (istream& is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);//这里的两个&&还不明白,请大神指点~~
istream& getline (istream& is, string& str);
istream& getline (istream&& is, string& str);
从函数声明可以看出,get line from stream to string.
①从输入流is中提取字符并保存进str中,直到遇到分隔符delimiter((2)中的分隔符,默认是'\n');
②当在输入操作遇到错误,或者end-of-file遇到时,停止提取;
③当分隔符delimiter找到时,它将被提取和丢弃,不会保存进str中,下一次的输入操作将从它之后开始;
在操作这里时,遇到一个小问题:
cout << "Input:";
getline(cin,word,'s');
cout << word << endl;
cout << "Input:";
getline(cin, str);
cout << str << endl;
If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it.这句是cpluscplus中的原话,但是,我在操作的时候发现,第二次的Input根本做不了,难道是s没有被丢弃,直接被第二次的getline()提取了?
但是,如果这样操作:
cout << "Input:";
getline(cin,word);
cout << word << endl;
cout << "Input:";
getline(cin, str);
cout << str << endl;
第二次的Input就可以继续进行,这是为什么?'\n'和单独的一个其他字符有什么区别吗?
④每一次提取的字符都将append至str中,类似于push_back()的操作。
istream::getline()
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
①从stream中以非规格化的input提取字符,并以C风格字符串的形式保存进字符数组s中,直到遇到分隔符delimiter,或者n个字符已经被写入s中(其实只有n-1个,‘\0’将被自动地追加在s后)。
②和string::getline()一样,当分隔符delimiter被找到时,它将会被提取,舍去,不会写入s。
在操作这里时,依旧遇到问题:
char s1[5];
char s2[5];
cin.getline(s1,5,'a');
cout << s1 << endl;
cin.getline(s2,5,'b');
cout << s2 << endl;
当我输入的数据是下面两种情况,输出结果不同,这是为什么?
第二种情况是因为failbit导致第二次的Input失败吗?
③当遇到end-of-file时,提取字符结束。而且,就算还没有写入到n个或者还没有遇到分隔符delimiter,也会结束,并设置eofbit标志。
④当getline()没有提取到字符,或者当n个字符已经写入到s中但是没有遇到分隔符delimiter,这时,failbit标志将被设置。但是,
if the character that follows those
(n-1)
characters in the input sequence is precisely the
delimiting character
, it is also extracted and the
failbit
flag is not set。