C ++忽略还是substr?

时间:2015-02-24 16:37:51

标签: c++ ignore

有以下输入:

10/10/2013 04:59:37 PM,7.21,6000,9050.00,LT XT

10/10/2013 10:04:14 AM,9.88,246,99946.56,

我使用getline函数来读取整行 使用

substr(0,2); // i am able to read 10,2013, 04 

我无法从','开始substr。我知道使用ignore函数会有效,有没有办法在','之后单独读取元素?

1 个答案:

答案 0 :(得分:0)

您可以使用find()substr()以逗号分隔字符串。

std::string line = "10/10/2013 10:04:14 AM,9.88,246,99946.56,";
std::vector<std::string> tokens;
size_t pos = 0;
size_t comma = line.find(",", pos);

while (comma != std::string::npos)
{
    tokens.push_back(line.substr(pos, comma - pos));
    pos = comma + 1;
    comma = line.find(",", pos);
}
// if there is anything left in the string after the last , add it to the vector
if (pos < line.size())
    tokens.push_back(line.substr(pos));