给定数据格式为“int,int,...,int,string,int”,是否可以使用stringstream(only)来正确解码字段?C++ stringstream将固定长度字符串读入字符数组
[代码]
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";
}
[输出]0:1:2:3:4:5:CT_6,0:-45689
,粗体部分表示字符串流未能读取4炭只有dcontact。 dcontact
实际上保持超过4个字符,留下垃圾数据j
。
http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in -c – user93353