_wtoi return zero: input zero or non-numerical input?

c++, visual-c++

Solution

This is C++, you should be using `stringstream` to do your conversion:

#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;
}

A cleaner and easier solution exists with boost's `lexical_cast`:

#include <boost/lexcal_cast.hpp>

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

If you insist on using C, `sscanf` can do this cleanly.

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

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

You can also use `strtol` with the caveat that it requires a little thinking. Yes, it'll return zero for both strings evaluating to zero and for error, but it also has an (optional) parameter `endptr` which will point to the next character after the numeric that's been converted:

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

if (*endPtr != NULL) {
    //error
}

Problem

_wtoi when can't convert input, so input isn't integer, returns zero. But the same time input can be zero. Is it a way to determine if there was wrong input or zero?

Original source

Related problems