How check if an input string is an integer

Hi everyone,

I got into another issue while trying to parse an integer.
This integer is received as part of a string eg: "num: 987"
where "num: " is fix and using substr() I get the "987"
The problem is I don't actually get only that, I also get "987kjshd"
A total of 8 characters (which my guess is the minimum array size for type string)
so I'm trying to figure how to ensure that I will be actually checking the "987" only. because the method I'm using it returns always false because there are extra characters in the string I'm evaluating.

Thanks again for the help!
You can use member function find_first_not_of. For example, let assume that you extracted already the substring that starts from a digit.

std::string s ="987kjshd";

std::string::size_type n = s.find_first_not_of( "0123456789" );

if ( n != std::string::npos ) s = s.substr( 0, n );
Without a stringstream object and converting to an actual integer. You could check the index of the string against the ascii, decimal value:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
	std::string str = "789sjhgdf";
	unsigned int index = 0;

	while( index < str.length() )
	{
		// Check against the ascii decimal values and don't run past the length of the string.
		if( ( str[ index ] > 47 ) && ( str[ index ] < 58 ) && ( index < str.length() ) )
		{
			std::cout << str[ index ] << " is a number.\n";
		}
		else
		{
			std::cout << str[ index ] << " was not a number.\n";
		}

		++index;
	}
	
	return 0;
}


7 is a number.
8 is a number.
9 is a number.
s was not a number.
j was not a number.
h was not a number.
g was not a number.
d was not a number.
f was not a number.


You can fine the ascii decimal values here:
http://www.asciitable.com/

Hope this helps.
Last edited on

@Lynx876

It is a bad approach because you are using magic numbers and there are another code systems as for example EBCDIC

At least it would be much better to write

if( ( str[ index ] >= '0' ) && ( str[ index ] <= '9' ) )
Last edited on
Thanks Vlad. I've never actually used anything else. Didn't really think about that!
You should not be getting junk characters as a result of substr. Note the second argument of substr(), it is length.
http://www.cplusplus.com/reference/string/string/substr/

The substr call should be something like this: (for your specific need)
substr( position, lengthOfString - position);
Last edited on
indeed LowestOne, it seems I was using the wrong length and that's why I was getting an string of fix length (8) rather than one of the exact length. Having said that I'm still trying to digest those null-end characters. I'm against the time right now, that's why I just used strings to manipulate char arrays, but I hope spend some time trying to understand that as well.

Thanks for the help once again!
Topic archived. No new replies allowed.