我们经常需要将string类型转换为int、long、double、float类型,cctype头文件提供了转换前的验证函数isdigit()和isxdigit()。经vs2010实验:
int main() { std::string strDigit="123.35"; std::string strXDigit="0x56"; char* szDigit="456.123"; char* szXDigit="0x57"; std::locale loc(""); if (isdigit(*szDigit)) { std::cout<<szDigit<<" is digit.\n"; } if (isdigit(*(strDigit.c_str()))) { std::cout<<strDigit<<" is digit.\n"; } if (isxdigit(*szXDigit)) { std::cout<<szXDigit<<" is hex.\n"; } if (isxdigit(*(strXDigit.c_str()))) { std::cout<<strXDigit<<" is hex.\n"; } return 0; }
程序输出:
123.35 is digit.
456.123 is digit.
0x56 is hex.
0x57 is hex.
如果不是使用*szDigit、*szXDigit、*(strDigit.c_str())、*(strXDigit.c_str()),而是使用szDigit、szXDigit、strDigit.c_str()、strXDigit.c_str(),则不能编译成功。
在vc2012中需要引用locale头文件,用法为
std::locale loc("");
isdigit(*szDigit,loc);
但是要用szDigit可以编译通过,但是不会得到正确的结果。