Given data format as “int,int,…,int,string,int”, is it possible to use stringstream (only) to properly decode the fields?
[Code]
int main(int c, char** v)
{
std::string line = "0,1,2,3,4,5,CT_O,6";
char delimiter[7];
int id, ag, lid, cid, fid, did, j = -12345;
char dcontact[4]; // <- The size of <string-field> is known and fixed
std::stringstream ssline(line);
ssline >> id >> delimiter[0]
>> ag >> delimiter[1]
>> lid >> delimiter[2]
>> cid >> delimiter[3]
>> fid >> delimiter[4]
>> did >> delimiter[5] // <- should I do something here?
>> dcontact >> delimiter[6]
>> j;
std::cout << id << ":" << ag << ":" << lid << ":" << cid << ":" << fid << ":" << did << ":";
std::cout << dcontact << "\n";
}
[Output] 0:1:2:3:4:5:CT_6,0:-45689, the bolded part shows the stringstream failed to read 4 char only to dcontact. dcontact actually hold more than 4 chars, leaving j with garbage data.
Yes, there is no specific overload of
operator >> (istream&, char[N])for N and there is forchar*so it sees that as the best match. The overload for char* reads to the next whitespace character so it doesn’t stop at the comma.You could wrap your dcontact in a struct and have a specific overload to read into your struct. Else you could use read, albeit it breaks your lovely chain of
>>operators.will work at that point.
To read up to a delimiter, incidentally, you can use
getline. (getwill also work butgetlinefree-function writing to astd::stringwill mean you don’t have to guess the length).(Note that other people have specified to use
getrather thanread, but this will fail in your case as you do not have an extra byte at the end of yourdcontactarray for a null terminator. IF you wantdcontactto be null-terminated then make it 5 characters and use ‘get` and the null will be appended for you).