【问题标题】:StringStream input with comma delimited string - know columns apriori带有逗号分隔字符串的 StringStream 输入 - 先验知道列
【发布时间】:2015-07-13 04:48:24
【问题描述】:

我有一个 csv,我想用 StringStream 逐行标记。关键是我先验地知道这些列会是什么样子。例如,假设我知道文件如下所示

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&lt;string&gt;

我不想每行都创建一个新向量。由于我先验地知道文件将包含哪些列,我可以以某种方式直接读入stringint 变量吗?像这样

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

据我所知,如果输入行是空格分隔的,而不是逗号分隔的,上面的代码就可以工作。

我无法控制输入。因此,简单地将原始字符串中的“空格”替换为“逗号”并不是一个理想的解决方案,因为我不知道输入是否已经有空格。

有什么想法吗?谢谢

【问题讨论】:

    标签: c++ csv tokenize stringstream


    【解决方案1】:

    您可以尝试只读取带有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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多