Reading quoted string in c++

不羁的心 提交于 2019-12-04 19:54:48

I often use this to read between quotes:

std::string skip; // throw this away
std::string foodName;
std::getline(std::getline(input, skip, '"'), foodName, '"');

The first std::getline reads up to (and removes) the first quote. It returns the input stream so you can wrap that in another std::getline that reads in your variable up to the closing quote.

For example like this:

#include <string>
#include <sstream>
#include <iostream>

std::istringstream input(R"~(
"Rigatoni" starch 2.99
"Mac & Cheese" starch 0.50
"Potato Salad" starch 3.59
"Fudge Brownie" sweet 4.99
"Sugar Cookie" sweet 1.50
)~");

int main()
{
    std::string skip; // dummy
    std::string foodName;
    std::string foodType;
    float foodValue;

    while(std::getline(std::getline(input, skip, '"'), foodName, '"') >> foodType >> foodValue)
    {
        std::cout << "food : " << foodName << '\n';
        std::cout << "type : " << foodType << '\n';
        std::cout << "value: " << foodValue << '\n';
        std::cout << '\n';
    }
}

Output:

food : Rigatoni
type : starch
value: 2.99

food : Mac & Cheese
type : starch
value: 0.5

food : Potato Salad
type : starch
value: 3.59

food : Fudge Brownie
type : sweet
value: 4.99

food : Sugar Cookie
type : sweet
value: 1.5

This becomes trivial with C++14's std::quoted:

std::string foodName, foodType;
double cost;
while (fs >> std::quoted(foodName) >> foodType >> cost)
{
}

Yes, this will correctly parse "some word" into some word. Don't have a C++14 capable compiler? (You should, Fedora 22 ships with GCC 5.1.0 for example) then use Boost. The standard library modelled std::quoted after this Boost component, so it should work just as fine.

There are some other problems in your code:

  1. Streams have a conversion operator to bool. This means you can do: if (!input.open(filename)) { ... }

  2. input.close() is redundant. The destructor will automatically close the stream.

  3. You don't check if the input is valid, i.e. if (!(input >> a >> b >> c)) { // error }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!