给定数据格式为“int,int,...,int,string,int”,是否可以(仅)使用 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";
}
[输出] ,粗体部分显示 stringstream 无法仅读取 4 char 到 dcontact。实际上持有超过 4 个字符,留下垃圾数据。0:1:2:3:4:5:CT_6,0:-45689
dcontact
j