There are several ways to do this. The method you tried does not work because there is no zero digit sitting at the read position in the stream. Thus, the input will fail, and the stream reset bit will be set. You loop forever, because you only check on eof. Read this for more information.
, std::strtol:
#include <iostream>
#include <string>
#include <experimental/optional>
std::experimental::optional<int> find_int_strtol( const std::string & s )
{
for( const char *p = s.c_str(); *p != '\0'; p++ )
{
char *next;
int value = std::strtol( p, &next, 10 );
if( next != p ) {
return value;
}
}
return {};
}
int main()
{
for( std::string line; std::getline( std::cin, line ); )
{
auto n = find_int_strtol( line );
if( n )
{
std::cout << "Got " << n.value() << " in " << line << std::endl;
}
}
return 0;
}
, , , , . . next p, - . . p 1 . , .
std::optional ++ 17, ++ 14. . .
.
- . . , . <regex>:
std::experimental::optional<int> find_int_regex( const std::string & s )
{
static const std::regex r( "(\\d+)" );
std::smatch match;
if( std::regex_search( s.begin(), s.end(), match, r ) )
{
return std::stoi( match[1] );
}
return {};
}
.