将多个单词提取到一个字符串变量 [英] Extract multiple words to one string variable

查看:62
本文介绍了将多个单词提取到一个字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::stringstream convertor("Tom Scott 25");
std::string name;   
int age;

convertor >> name >> age;

if(convertor.fail())
{
    // it fails of course
}

我想将两个或多个单词提取到一个字符串变量中.到目前为止,我已经读过,看来这是不可能的.如果是这样,还应该怎么做?我希望 name 能够获取数字(年龄)之前的所有字符.

I'd like to extract two or more words to one string variable. So far I've read, it seems that it is not possible. If so, how else to do it? I'd like name to get all characters before number (the age).

使用sscanf使我感到最舒服,但是我显然不能.

I'd feel most comfortable using sscanf, but I obviously can't.

我需要的是能够提取例如 age 之前的所有单词的功能.

What I need is ability to extract all words before age for example.

推荐答案

到目前为止,大多数已发布的解决方案都不符合规范-直到年龄的所有数据都被视为名称.例如,它们将以"Richard Van De Rothstyne"之类的名字失败.

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".

OP指出,使用scanf可以执行以下操作: scanf(%[^ 0-9]%d",name,& age); ,它将读取此内容正好.假设这是面向行的输入,那么我还是倾向于这样做:

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:

std::string temp;
std::getline(infile, temp);

// technically "[^0-9]" isn't required to work right...
sscanf(temp.c_str(), "%[^0123456789] %d", name, &age);

不幸的是,iostream并没有提供类似于scanset转换的直接模拟-getline可以读取一个分隔符,但是您只能指定一个字符作为分隔符.如果您真的不能使用scanf和company,那么下一站将是手工编码(年龄的开始是 temp.find_first_of("0123456789"); )或使用RE软件包(如果编译器提供,则为TR1,否则可能提升).

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).

这篇关于将多个单词提取到一个字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆