Parsing command line arguments in a unicode C++ ap

2019-02-12 18:56发布

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't use atoi. How can I convert it to an integer? Is stringstream the best option?

4条回答
祖国的老花朵
2楼-- · 2019-02-12 19:24

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.

查看更多
虎瘦雄心在
3楼-- · 2019-02-12 19:35

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;
    }
}
查看更多
Emotional °昔
4楼-- · 2019-02-12 19:36

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]);
查看更多
你好瞎i
5楼-- · 2019-02-12 19:36

Dry coded and I don't develop on Windows, but using TCLAP, this should get you running with wide character argv values:

#include <iostream>

#ifdef WINDOWS
# define TCLAP_NAMESTARTSTRING "~~"
# define TCLAP_FLAGSTARTSTRING "/"
#endif
#include "tclap/CmdLine.h"

int main(int argc, _TCHAR *argv[]) {
  int myInt = -1;
  try {
    TCLAP::ValueArg<int> intArg;
    TCLAP::CmdLine cmd("this is a message", ' ', "0.99" );
    cmd.add(intArg);
    cmd.parse(argc, argv);
    if (intArg.isSet())
      myInt = intArg.getValue();
  } catch (TCLAP::ArgException& e) {
    std::cout << "ERROR: " << e.error() << " " << e.argId() << endl;
  }
  std::cout << "My Int: " << myInt << std::endl;
  return 0;
}
查看更多
登录 后发表回答