views:

3234

answers:

3

Hi folks,

How can i parse integers passed to an application as command line arguments if the app is unicode?

Unicode apps have a main like this:

int _tmain(int argc, _TCHAR* argv[])

argv[?] is a wchar_t*. That means i can´s use atoi. How can i convert it to an integer? is stringstream the best option?

+3  A: 

if you have a TCHAR array or a pointer to the begin of it, you can use std::basic_istringstream to work with it:

std::basic_istringstream<_TCHAR> ss(argv[x]);
int number;
ss >> number;

Now, number is the converted number. This will work in ANSI mode (_TCHAR is typedef'ed to char) and in Unicode (_TCHAR is typedef`ed to wchar_t as you say) mode.

Johannes Schaub - litb
+1  A: 

A TCHAR is a character type which works for both ANSI and Unicode. Look in the MSDN documentation (I'm assuming you are on Windows), there are TCHAR equivalents for atoi and all the basic string functions (strcpy, strcmp etc.)

The TCHAR equivalient for atoi() is _ttoi(). So you could write this:

int value = _ttoi(argv[1]);
Adam Pierce
that does not sound too platform indepedent...
David Reis
A: 

I personally would use stringstreams, here's some code to get you started:

#include <sstream>
#include <iostream>

using namespace std;

typedef basic_istringstream<_TCHAR> ITSS;

int _tmain(int argc, _TCHAR *argv[]) {

    ITSS s(argv[0]);
    int i = 0;
    s >> i;
    if (s) {
        cout << "i + 1 = " << i + 1 << endl;
    }
    else {
        cerr << "Bad argument - expected integer" << endl;
    }
}
Frank Krueger