将多个单词提取到一个字符串变量
std::stringstream convertor("Tom Scott 25");
std::string name;
int age;
convertor >> name >> age;
if(convertor.fail())
{
// it fails of course
}
我想将两个或多个单词提取到一个字符串变量中。到目前为止我读过,似乎这是不可能的。如果是的话,还有什么办法呢?我希望 name
获取数字(年龄)之前的所有字符。
我觉得使用 sscanf 最舒服,但我显然不能。
例如,我需要能够提取 age
之前的所有单词。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
到目前为止发布的大多数解决方案并没有真正满足规范——所有截止日期的数据都被视为名称。例如,他们会因为“Richard Van De Rothstyne”这样的名字而失败。
正如OP所指出的,使用 scanf 你可以执行类似的操作:
scanf("%[^0-9] %d", name, &age);
,它会很好地读取它。假设这是面向行的输入,无论如何我都会这样做:不幸的是,iostreams 不提供对扫描集转换的直接模拟—— getline 可以读取到一个分隔符,但你只能指定一个字符为分隔符。如果您确实无法使用 scanf 和 company,那么下一站将是手动编码(时代的开始将是
temp.find_first_of("0123456789");
)或使用 RE包(TR1,如果你的编译器提供它,否则可能 增强)。Most of the solutions posted so far don't really meet the specification -- that all the data up to the age be treated as the name. For example, they would fail with a name like "Richard Van De Rothstyne".
As the OP noted, with scanf you could do something like:
scanf("%[^0-9] %d", name, &age);
, and it would read this just fine. Assuming this is line oriented input, I'd tend to do that anyway:Unfortunately, iostreams don't provide a direct analog to a scanset conversion like that -- getline can read up to a delimiter, but you can only specify one character as the delimiter. If you really can't use scanf and company, the next stop would be either code it by hand (the beginning of the age would be
temp.find_first_of("0123456789");
) or use an RE package (TR1 if your compiler supplies it, otherwise probably Boost).这有什么问题吗?
What’s wrong with this?
这有什么问题吗?
如果你真的想一次性阅读第一个和最后一个,类似这样的东西会起作用
一个更通用的例子,你想阅读 N 个单词可以像这样运行:
What's wrong with this?
If you really want to read first and last in one go, something like this will work
A more generic example where you wanted to read N words could function like this:
您可以实现的通用算法:
General algorithm that you could implement:
一种方法是创建一个带有重载运算符>>的新类。
One approach would be to make a new class with an overloaded operator>>
这是过度杀伤的方法(使用 Boost.Spirit< /a>) >:D
输出:
不过说真的,如果您经常在程序中进行重要的输入解析,请考虑使用 解析 或 正则表达式库。
Here's the overkill way (using Boost.Spirit) >:D
Output:
Seriously though, if you often do non-trivial input parsing in your program, consider using a parsing or regular expressions library.
这是我刚刚做的作业。
但 int 或 double 类型必须放在字符串前面。因此您可以阅读不同大小的多个单词。
希望这可以帮助你一点点。
This is an homework i just did.
But int or double types have to placed in front of the the string. therefor you can read multiple words at different size.
Hope this can help you a little bit.
这是一个带有
std::regex
(任意数量的名称)的解决方案:测试:
输出:
Here it is an solution with
std::regex
(any number of names):Test:
Output: