【问题标题】:Is there a way to getline just part of a line?有没有办法只获取一行的一部分?
【发布时间】:2018-11-07 09:43:42
【问题描述】:

我想不出更好的标题,但让我解释一下。

我有一个这样的文件

potions.txt 药水 配料.txt 配料

INSERT((Red Mountain Flower|0.1|2|Yes|No|Mountains,Forests),ingredients)
INSERT((Abecean Longfin|0.5|15|No|Yes|Rivers,Lakes),ingredients)
INSERT((48|Glibness|Fortify|+20 Speechcraft for 60 seconds.|96|None|None),potions)
UPDATE((Abecean Longfin|0.5|15|No|Yes|Rivers,Lakes,Swamps),ingredients)
UPDATE((205|Minor Healing|Health|Restore 25 points of Health.|17|Blue Mountain Flower|Charred Skeever Hide),potions)
UPDATE((206|Healing|Health|Restore 50 points of Health.|36|Blue Mountain Flower|Swamp Fungal Pod),potions)
SELECT((9|*|*|*|*|*|*),potions)
INSERT((Purple Mountain Flower|0.1|2|Yes|No|Mountains,Forests),ingredients)

我正在尝试解析文件以将正确的内容存储到正确的变量中。

所以,我试着写

for(int i = 0; i < num_of_lines; i++)
{
        getline(inputFile, insert, '(');
        if(insert == "INSERT")
        {
            cout << insert << endl;
        }
}

我马上就知道我的问题了。当 for 循环继续时,它将读取内容的顺序是

(
Red Mountain Flower|0.1|2|Yes|No|Mountains,Forests),ingredients)INSERT(
(Abecean Longfin|0.5|15|No|Yes|Rivers,Lakes),ingredients)INSERT(

意味着它永远不会读取另一个“插入”,因此我永远无法访问它以进一步解析文件。

有没有办法只获取一行的一部分,以便如果字符串匹配,我可以继续解析文件?我尝试过查找函数,我尝试过字符串比较函数,但我似乎无法得到任何工作。任何有关我如何解决此问题的建议将不胜感激。

【问题讨论】:

  • 逐行阅读,然后使用两个getlines() 即可。
  • 逐行读取,然后对所有行使用状态机方法。或者你可以使用正则表达式(尽管 __cplusplus &lt;= 2011xxxx 它们不是内置的)。

标签: c++ string getline


【解决方案1】:

输入显然是基于行的,所以逐行读取,然后解析这些行:

for(int i = 0; i < num_of_lines; i++)
{
        getline(inputFile, lineText);
        std::istringstream line(lineText);

        // Now, work with `line` as your stream
        getline(line, insert, '(');
        if(insert == "INSERT")
        {
            cout << insert << endl;
        }
}

【讨论】:

  • 看起来线条遵循固定模式 - 正则表达式可能是解析的好选择......
猜你喜欢
  • 2021-07-02
  • 2021-12-17
  • 2019-10-30
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 2020-02-17
  • 2013-12-09
相关资源
最近更新 更多