C++判断是不是数字的两种方法,可以判断正负数,小数。

#include <iostream>
#include <sstream>  
using namespace std;

bool isNum(string str);
bool isNumber(const string& str);
int main(void)
{
	string str1 = "-255332";
	string str2 = "-1990.2363";
	if (isNum(str1))
	{
		cout << "str1 is a num" << endl;
	}
	else
	{
		cout << "str1 is not a num" << endl;

	}
	if (isNumber(str2))
	{
		cout << "str2 is a num" << endl;
	}
	else
	{
		cout << "str2 is not a num" << endl;

	}

	cin.get();
	return 0;
}

bool isNumber(const string& str)
{
	return str.find_first_not_of("-0123456789.") == string::npos;
}
bool isNum(string str)
{
	stringstream sin(str);
	double d;
	char c;
	if (!(sin >> d))
	{
		return false;
	}
	if (sin >> c)
	{
		return false;
	}
	return true;
}


Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐