C++ wstring判断字符串是否为数字
时间: 2023-09-24 12:02:30 浏览: 54
可以使用C++标准库中的`std::wstringstream`来实现判断wstring字符串是否为数字:
```c++
#include <iostream>
#include <sstream>
#include <locale>
using namespace std;
bool is_number(const wstring& str)
{
wistringstream ss(str);
double num;
ss.imbue(locale("")); //设置本地化环境,以支持数字格式中的逗号和小数点
ss >> num;
return !ss.fail() && ss.eof(); //如果转换失败或者还有多余字符,表示不是数字
}
int main()
{
wstring str1 = L"123"; //数字字符串
wstring str2 = L"abc"; //非数字字符串
if (is_number(str1))
wcout << L"str1是数字" << endl;
else
wcout << L"str1不是数字" << endl;
if (is_number(str2))
wcout << L"str2是数字" << endl;
else
wcout << L"str2不是数字" << endl;
return 0;
}
```
输出结果:
```
str1是数字
str2不是数字
```