【发布时间】:2015-10-12 02:16:47
【问题描述】:
我正在尝试从文件中读取带引号的字符串并将其存储在字符串中。我正在从文件中读取字符串,输入文件是这样的:
"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 中的其他类似主题,但找不到适合我的问题的解决方案
【问题讨论】: