我有一个csv,我想用StringStream逐行标记。关键是我知道apriori列的样子。例如,假设我知道该文件如下所示
StrHeader,IntHeader
abc,123
xyz,456
我提前知道它是一个字符串列,后跟一个int列。
常用方法是逐行读取文件
std::string line;
stringstream lineStream;
while (getline(infile, line)) // read line by line
{
cout << "line " << line << endl;
lineStream << line;
string token;
while(getline(lineStream, token, ',')) // push into vector? this is not ideal
{
}
我知道我可以有2个循环,并且内部循环基于逗号对字符串进行标记。 stackoverflow上的大量示例代码会将结果存储到vector<string>
。
我不想每行创建一个新的向量。既然我知道apriori文件会有哪些列,我可以以某种方式直接读入string
和int
变量吗?喜欢这个
std::string line;
stringstream lineStream;
while (getline(infile, line)) // read line by line
{
cout << "line " << line << endl;
lineStream << line; // DOESNT WORK - tell lineStream we have comma delimited string
string strValue;
int intValue;
lineStream >> strValue >> intValue; // SO MUCH CLEANER
// call foo(strValue, intValue);
}
上面的问题是这一行
lineStream << line; // DOESNT WORK - tell lineStream we have comma delimited string
据我所知,如果输入行是以空格分隔的,而不是以逗号分隔,则上述代码有效。
我无法控制输入。因此,简单地用原始字符串中的“逗号”替换“空格”不是理想的解决方案,因为我不知道输入是否已经有空格。
有什么想法吗?感谢
答案 0 :(得分:0)
您可以尝试仅使用std::getline()
读取分隔符,然后将其放入字符串流中进行转换。
while (!infile.eof()){
std::getline(infile, strValue, ',');
std::getline(infile, line);
strstr.str(line);
strstr.clear();
int intValue;
strstr >> intValue;
foo(strValue, intValue);
}