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

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

Member Avatar for jencas

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;
}

*Mumbles something about multiple exit points*

You can do that:

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

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

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

inline bool isUint(const std::string& s)
{
    return s.find_first_not_of("0123456789") == std::string::npos;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.