4

_wtoi当无法转换输入,因此输入不是整数时,返回零。但同时输入可以为零。这是一种确定输入错误还是零的方法吗?

4

1 回答 1

4

这是 C++,您应该使用它stringstream来进行转换:

#include <iostream>
#include <sstream>

int main()
{
   using namespace std;

   string s = "1234";
   stringstream ss;

   ss << s;

   int i;
   ss >> i;

   if (ss.fail( )) 
   {
        throw someWeirdException;
   }
   cout << i << endl;

   return 0;
}

boost's 存在一个更清洁、更简单的解决方案lexical_cast

#include <boost/lexcal_cast.hpp>

// ...
std::string s = "1234";
int i = boost::lexical_cast<int>(s);

如果您坚持使用C,sscanf可以干净地做到这一点。

const char *s = "1234";
int i = -1;

if(sscanf(s, "%d", &i) == EOF)
{
    //error
}

你也可以使用strtol它需要一点思考的警告。是的,对于评估为零的字符串和错误,它都会返回零,但它还有一个(可选)参数endptr,它将指向转换后的数字之后的下一个字符:

const char *s = "1234";
const char *endPtr;
int i = strtol(s, &endPtr, 10);

if (*endPtr != NULL) {
    //error
}
于 2012-05-21T16:54:52.530 回答