转自:http://zhidao.baidu.com/question/445168607.html 百度知道
标题:c++中怎么判断一个string类型的字符串变量是否为数字?
stringstream字符流除了可以在各种数据类型之间实现转换或者格式化之外,还可判断字符串中是否全是数字,如下:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
bool isnum(string s)
{
stringstream sin(s);
double t;
char p;
if(!(sin >> t))
return false;
if(sin >> p)
return false;
else
return true;
}
int main()
{
string s;
while(cin >> s)
{
if(isnum(s))
cout << s << " is a number." << endl;
else
cout << s << " is not a number." << endl;
}
}