c++ - 字符串流问题

标签 c++ delimiter istringstream

问题:

我有一个文本文件,其中包含下面“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/

相关文章:

c++ - 在 C++ 中的字符串中搜索字符串

c++ - 在多行中用相应的元素格式化 C++ 代码

c++ - 使用 Alpha channel 复制 SDL_Surfaces

java - 如何使用Scanner的分隔符方法

C++ getline() 的未记录行为

c++ - do...while() 重复最后一个字符串两次

c++ - 有没有一种方法可以在不下载整个文件的情况下确定托管在 HTTP 服务器上的文件的版本?

c++ - Google模拟和替代关键字

python - 使用数组中的多个分隔符拆分字符串 (Python)

java - 如何使用正则表达式从字符串中删除外部标点符号