In C++ when you use getline()
with delimiter on stringstream there are few things that I didn't found documented, but they have some non-error handy behaviour when:
- delimiter is not found => then simply whole string/rest of it is returned
- there is delimiter but nothing before it => empty string is returned
- getting something that isn't really there => returns the last thing that could be read with it
Some test code (simplified):
#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;
}
Test code output:
'something without delimiter'
'321'
''
'123'
'123'
Test code fiddle: http://ideone.com/ZAuydR
The Question
The question is - can this be relied on? If so, where is it documented - is it?
Thanks for answers and clarifying :)