there is a string string, for example

string str ="ddadsadwd 1337 dsdggf"; 

you need to find a number in it and write to the variable int

  • Follow the line to the first digit. This is the expected beginning of a number, move on to the space or the end of the line - this is the end of the number entry. - Alexey Sarovsky
  • @ AlekseySarovsky can write as a code? Or what functions can be used - topl3niy
  • cplusplus.com/reference/string/string/find_first_of Further to paint - completely unsportsmanlike. - PinkTux
  • I didn’t understand @PinkTux, I’ll find the beginning of a number, but how do I write it into a variable? - topl3niy
  • And a little further documentation to look through the standard library - not? - PinkTux

3 answers 3

 #include <iostream> #include <string> #include <cstdlib> int main(void) { std::string s ="ddadsadwd 1337 dsdggf"; size_t digits = s.find_first_of( "1234567890+-" ); if( digits <= s.size() ) { std::cout << "Number found: " << atoi( s.c_str() + digits ) << std::endl; } else { std::cout << "Number is not found" << std::endl; } return 0; } 

    There are several ways to solve the problem. One of the straightforward ways might look like this

     #include <iostream> #include <algorithm> #include <cctype> #include <cstdlib> int main() { std::string str ="ddadsadwd 1337 dsdggf"; int n = 0; auto it = std::find_if( str.begin(), str.end(), isdigit ); if ( it != str.end() ) n = std::atoi( str.c_str() + ( it - str.begin() ) ); std::cout << n << std::endl; return 0; } 

    Output of the program to the console

     1337 

    It is assumed that the number in the string does not contain a sign. Otherwise, you will have to use another predicate in the std::find_if , which will also check for the sign of the number.

    • writes it doesn’t name a type - topl3niy
    • @ topl3niy In which sentence does this error occur? - Vlad from Moscow
    • where you initialize auto it - topl3niy
    • @ topl3niy The code should compile successfully if you copied it without errors. You can also replace auto it with std :: string :: iterator it - Vlad from Moscow
    • @ topl3niy probably makes sense to use c ++ 11 in 2016 (the --std == c ++ 11 flag) - int3

    Option with regex :

     #include <iostream> #include <string> #include <regex> using namespace std; int main() { string s = "ddadsadwd 1337 dsdggf"; regex p("\\d+"); regex_token_iterator<string::iterator> numbers( s.begin(), s.end(), p ); string t = *numbers; int first_number = atoi( t.c_str() ); cout << first_number << endl; return 0; } 

    PS Why doesn't it work (*numbers).c_str() ?