您好 我知道有很多次被问过,但我没有找到答案。
我想只转换只包含十进制数字的字符串:
例如256可以,但256a不是。
可以在不检查字符串的情况下完成吗?
由于
答案 0 :(得分:14)
使我能想到的错误检查可选的最简单方法是:
char *endptr;
int x = strtol(str, &endptr, 0);
int error = (*endptr != '\0');
答案 1 :(得分:7)
以C ++方式,使用stringstream
:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
stringstream sstr;
int a = -1;
sstr << 256 << 'a';
sstr >> a;
if (sstr.failbit)
{
cout << "Either no character was extracted, or the character can't represent a proper value." << endl;
}
if (sstr.badbit)
{
cout << "Error on stream.\n";
}
cout << "Extracted number " << a << endl;
return 0;
}
答案 2 :(得分:6)
使用c ++样式的另一种方法:我们检查数字位数,以确定该字符串是否有效:
#include <iostream>
#include <sstream>
#include <string>
#include <cmath>
int main(int argc,char* argv[]) {
std::string a("256");
std::istringstream buffer(a);
int number;
buffer >> number; // OK conversion is done !
// Let's now check if the string was valid !
// Quick way to compute number of digits
size_t num_of_digits = (size_t)floor( log10( abs( number ) ) ) + 1;
if (num_of_digits!=a.length()) {
std::cout << "Not a valid string !" << std::endl;
}
else {
std::cout << "Valid conversion to " << number << std::endl;
}
}