如何在 std::getline 中自定义分隔符

how to customize the delimiter in std::getline

本文关键字:自定义 分隔符 getline std      更新时间:2023-10-16

我正在解决hackerRank上的属性解析器,但我被定界符困住了。我想从("任何事物"(中获取一个元素,在这种情况下,它会给我(任何事物(,但是当我这样做时:

while (getline(ob, item, '""')) {//but its be true when i put single one ('"')
std::cout << item << "n";
}

它给了我这个错误:

E0304 没有"getline"实例与参数列表匹配

正如@RetiredNinja所说,您可以使用'"'作为分隔符。代码可能如下所示:

#include <iostream>
#include <string>

int main()
{
std::string str;
while (std::getline(std::cin, str, '"'))
if (!str.empty() && str[0] != '(' && str[0] != ')')
std::cout << '(' << str << ")n";
}

您可以根据问题的规则更改代码。请注意,分隔符会首先为您提供"(",然后是实际单词,依此类推。因此,您必须过滤您不感兴趣的值。