【发布时间】:2015-11-24 17:17:12
【问题描述】:
在 C++ 中,当您在 stringstream 上使用带有分隔符的 getline() 时,几乎没有我发现记录在案的事情,但在以下情况下它们有一些非错误的方便行为:
- 没有找到分隔符 => 然后简单地返回整个字符串/其余部分
- 有分隔符,但之前没有任何内容 => 返回空字符串
- 得到不存在的东西 => 返回最后可以用它读取的东西
一些测试代码(简化):
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string test(const string &s, char delim, int parseIndex ){
stringstream ss(s);
string parsedStr = "";
for( int i = 0; i < (parseIndex+1); i++ ) getline(ss, parsedStr, delim);
return parsedStr;
}
int main() {
stringstream ss("something without delimiter");
string s1;
getline(ss,s1,';');
cout << "'" << s1 << "'" << endl; //no delim
cout << endl;
string s2 = "321;;123";
cout << "'" << test(s2,';',0) << "'" << endl; //classic
cout << "'" << test(s2,';',1) << "'" << endl; //nothing before
cout << "'" << test(s2,';',2) << "'" << endl; //no delim at the end
cout << "'" << test(s2,';',3) << "'" << endl; //this shouldn't be there
cout << endl;
return 0;
}
测试代码输出:
'something without delimiter'
'321'
''
'123'
'123'
测试代码小提琴:http://ideone.com/ZAuydR
问题
问题是 - 这可以依靠吗?如果是这样,它记录在哪里 - 是吗?
感谢您的回答和澄清:)
【问题讨论】:
-
您找到了哪些文档?是的,所有行为都完全记录在 C++ 标准中。
-
它的记录也大致相同here。
标签: c++ stream getline stringstream istringstream