parksumin
parksumin

Reputation: 11

How can search number in string?

Hello? I want to know how can I find number in my string code. This is my c++ code.

    string firSen;
    cout<<"write the senctence : "<<endl;
    getline(cin,firSen);
    int a=firSen.find("pizza");
    int b=firSen.find("hamburger");
    int aa=firSen.find(100);
    int bb=firSen.find(30);

I want to write

 I want to eat pizza 100g, hamburger 30g!!

and I want to know 100 and 30 address.

I know how to find pizza and hamburger address.(It's the right code)

but I don't know how to find number..(I think int aa=firSen.find(100); int bb=firSen.find(30); is wrong code)

Could you help me?

Upvotes: 0

Views: 652

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

The std::string::find() function takes a std::string or a const char* as valid search keys.

If you want to search for 'generic numbers' you'll have to convert them to a std::string or use a const char* literal

 size_type aa=firSen.find("100");

or

 int num = 100;
 size_type aa=firSen.find(std::to_string(num));

See the std::to_string() function reference


As it looks from your input sample, you don't know the numeric values beforehand, thus looking up something like

 size_type aa=firSen.find("100");

renders useless.
What you actually need is some decent parser, that enables you reading the numeric values after some certain keywords, that require a numeric attribute (like weight in your sample).

The simplest way might be, to find your keywords like "hamburger" or "pizza", and move on from the found position, to find the next digit ('0-9'), and extract the number from that position.

Using std::regex as proposed in @deeiip's answer, might be a concise solution for your problem.

Upvotes: 2

deeiip
deeiip

Reputation: 3379

I'd use this in your situation (if I was searching for just a number, not a specific number):

std::regex rgx("[0-9]+");
std::smatch res;
while (std::regex_search(firSen, res, rgx)) {
    std::cout << res[0] << std::endl;
    s =  res.suffix().str();
}

This is c++11 standard code using <regex>. What it does is: search for any occurence of a number. This is what [0-9]+ means. And It keep on searching for this pattern in your string.


This solution should only be used when I dont know what number I'm expecting otherwise it'll be much more expensive than other solution mentioned.

Upvotes: 2

Related Questions