Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract multiple words to one string variable

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

convertor >> name >> age;

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

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

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

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

like image 900
kjagiello Avatar asked Jan 31 '26 01:01

kjagiello


1 Answers

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:

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

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

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

like image 52
Jerry Coffin Avatar answered Feb 02 '26 15:02

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!