方法一:判断字符的ASCII范围(数字的范围为48~57)
#include <iostream>
using namespace std;
bool AllisNum(string str);
int main( void )
{
string str1 = "wolaiqiao23";
string str2 = "1990";
if (AllisNum(str1))
{
cout<<"str1 is a num"<<endl;
}
else
{
cout<<"str1 is not a num"<<endl;
}
if (AllisNum(str2))
{
cout<<"str2 is a num"<<endl;
}
else
{
cout<<"str2 is not a num"<<endl;
}
cin.get();
return 0;
}
bool AllisNum(string str)
{
for (int i = 0; i < str.size(); i++)
{
int tmp = (int)str[i];
if (tmp >= 48 && tmp <= 57)
{
continue;
}
else
{
return false;
}
}
return true;
}
#include <iostream>
#include <sstream>
using namespace std;
bool isNum(string str);
int main( void )
{
string str1 = "wolaiqiao23r";
string str2 = "1990";
if(isNum(str1))
{
cout << "str1 is a num" << endl;
}
else
{
cout << "str1 is not a num" << endl;
}
if(isNum(str2))
{
cout<<"str2 is a num"<<endl;
}
else
{
cout<<"str2 is not a num"<<endl;
}
cin.get();
return 0;
}
bool isNum(string str)
{
stringstream sin(str);
double d;
char c;
if(!(sin >> d))
{
/*解释:
sin>>t表示把sin转换成double的变量(其实对于int和float型的都会接收),
如果转换成功,则值为非0,如果转换不成功就返回为0
*/
return false;
}
if (sin >> c)
{
/*解释:
此部分用于检测错误输入中,数字加字符串的输入形式(例如:34.f),在上面的的部分(sin>>t)
已经接收并转换了输入的数字部分,在stringstream中相应也会把那一部分给清除,
此时接收的是.f这部分,所以条件成立,返回false
*/
return false;
}
return true;
}