轉自: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;
}
}