0

Hi,

I'm having problems checking whether a string is an unsigned integer. The code I am using only checks the first character of the string, so "a1" would return false, but "1a" would return true. Any ideas where I'm going wrong?

bool checkUnsignedInt(string *str)
{
	unsigned long value;
	stringstream ss(*str);

	if (ss >> value)
	{
		return true;
	}
	else
	{
		return false;
	}
}

Thanks

7
Contributors
7
Replies
8
Views
8 Years
Discussion Span
Last Post by ArkM
0

What exactly is the problem? this works fine for me....nvm

EDIT:
of you need to loop through each character rather than just using the first one

Chris

0

Maybe something like this comes helpful:

bool checkUnsignedInt(string *str)
{
	unsigned long value;
	stringstream ss(*str);

	if (ss >> value)
	{
                string str;
                ss >> str;
                return str.empty(); // nothing following the digits
	}
	return false;
}
0

You can do that:

bool checkUnsignedInt(const string &str)
{
	return atoi(str.c_str()) >= 0;
}
0

I think you can simply check if the first character is a numeral.

Thats what his code does, but that doesn't mean that "1dfjkghdflgh" is an integer, because it isn't. But by your logic it would be.

Chris

0
inline bool isUint(const std::string& s)
{
    return s.find_first_not_of("0123456789") == std::string::npos;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.