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
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
#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.
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() ?
Source: https://ru.stackoverflow.com/questions/593470/
All Articles