问题:
我有一个文本文件,其中包含下面“txt 文件”下需要的信息行。我正在尝试绘制项目 map 以便完成作业。在映射它们时,我使用了 istringstream
。当我想在一个字符串中保存的项目中有多个单词时,我的问题就在于让它工作。例如“不加糖的苹果酱”,我希望它是一个字符串 (item.setNewItem)。任何帮助都将不胜感激,而且由于我是一名在读学生,为我着想的任何简化都将不胜感激。 =)
txt 文件:
1 杯糖 | 1 杯不加糖的苹果酱 |卡路里
代码:
void mapList(ifstream &foodReplace, map<string, Substitutions> &subs)
{
string line;
while (getline (foodReplace, line));
{
Substitutions item;
istringstream readLine(line);
readLine << item.setOldAmount
<< item.setOldMeasurement
<< item.setOldItem
<< item.setNewAmount
<< item.setNewMeasurement
<< item.setNewItem;
subs.insert(pair<string, Substitutions>(item.getOldItem, item));
}
}
最佳答案
您可以只向 getline 提供第三个参数来指定分隔符:
http://www.cplusplus.com/reference/string/string/getline/
然后你可以将第一个和第二个字段读取到' ',将第三个字段读取到'|'。
通话内容如下:
void mapList(ifstream &foodReplace, map<string, Substitutions> &subs)
{
string line;
while (getline (foodReplace, line));
{
Substitutions item;
istringstream readLine(line);
getline(readLine, item.setOldAmount, ' '); //you may need to read this in to a temp string if setOldAmount is an int
getline(readLine, item.setOldMeasurement, ' ');
getline(readLine, item.setOldItem, '|');
getline(readLine, item.setNewAmount, ' '); //you may need to read this in to a temp string if setNewAmount is an int
getline(readLine, item.setNewMeasurement, ' ');
getline(readLine, item.setNewItem, '|');
subs.insert(pair<string, Substitutions>(item.getOldItem, item));
}
}
关于c++ - 字符串流问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23024175/