[英]Reading quoted string in c++
我正在尝试从文件中读取带引号的字符串并将其存储在字符串中。 我正在从文件中读取字符串,输入文件是这样的:
"Rigatoni" starch 2.99
"Mac & Cheese" starch 0.50
"Potato Salad" starch 3.59
"Fudge Brownie" sweet 4.99
"Sugar Cookie" sweet 1.50
我试图做几件事:
1。
input.open(filename);
if (input.fail())
{
std::cout << "File is not found!";
exit(1);
}
else
{
std::string foodName = ""; std::string foodType = "";
double cost;
input >> foodName >> foodType >> cost;
foodName = foodName.substr(1, foodName.size()-2);
std::cout << foodName << " " << foodType << " " << cost << std::endl;
}
input.close();
此版本仅适用于第一行。 第一行之后,我没有得到完整的引号。 另一个版本读取整个引用的单词,但是,后面的单词和数字是分开的。
input.open(filename);
if (input.fail())
{
std::cout << "File is not found!";
exit(1);
}
else
{
std::string line = "";
while (std::getline(input, line, '\n')) //delimeter is new line
{
if (line != "")
{
std::stringstream stream(line);
std::string foodName = "";
while (std::getline(stream, foodName, '"') ) //delimeter is double quotes
{
std::cout << "current word " << foodName << std::endl;
}
}
}
} input.close();
我的目标是阅读3个单独的单词。 我在stackoverflow中查看了其他类似的主题,但找不到适合我问题的正确解决方案
这对于C ++ 14的std::quoted
是微不足道的:
std::string foodName, foodType;
double cost;
while (fs >> std::quoted(foodName) >> foodType >> cost)
{
}
是的,这将正确地将"some word"
解析为some word
。 没有具有C ++ 14功能的编译器? (例如,Fedora 22随附GCC 5.1.0),然后使用Boost 。 标准库在此Boost组件之后std::quoted
建模,因此它应该也可以正常工作。
您的代码中还有其他一些问题:
流具有转换为bool的运算符。 这意味着您可以执行以下操作: if (!input.open(filename)) { ... }
input.close()
是多余的。 析构函数将自动关闭流。
您不检查输入是否有效,即if (!(input >> a >> b >> c)) { // error }
我经常用它来读引号之间:
std::string skip; // throw this away
std::string foodName;
std::getline(std::getline(input, skip, '"'), foodName, '"');
第一个std :: getline读取(并删除)第一个引号。 它返回输入流,因此您可以将其包装在另一个std :: getline中 ,该变量读取变量直至结束引号。
例如这样:
#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';
}
}
输出:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.