简体   繁体   English

在unicode C ++应用程序中解析命令行参数

[英]Parsing command line arguments in a unicode C++ application

How can I parse integers passed to an application as command line arguments if the app is unicode? 如果应用程序是unicode,如何解析传递给应用程序的整数作为命令行参数?

Unicode apps have a main like this: Unicode应用程序有这样的主要:

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

argv[?] is a wchar_t*. argv [?]是一个wchar_t *。 That means i can't use atoi. 这意味着我不能使用atoi。 How can I convert it to an integer? 如何将其转换为整数? Is stringstream the best option? stringstream是最好的选择吗?

if you have a TCHAR array or a pointer to the begin of it, you can use std::basic_istringstream to work with it: 如果你有一个TCHAR数组或指向它的开头的指针,你可以使用std::basic_istringstream来处理它:

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

Now, number is the converted number. 现在, 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. 这将工作在ANSI模式(_TCHAR是typedef'ed到char )和Unicode(_TCHAR是typedef`ed到wchar_t,如你所说)模式。

A TCHAR is a character type which works for both ANSI and Unicode. TCHAR是一种适用于ANSI和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.) 查看MSDN文档(我假设您在Windows上),atoi和所有基本字符串函数(strcpy,strcmp等)都有TCHAR等价物。

The TCHAR equivalient for atoi() is _ttoi(). atoi()的TCHAR等价是_ttoi()。 So you could write this: 所以你可以这样写:

int value = _ttoi(argv[1]);

Dry coded and I don't develop on Windows, but using TCLAP , this should get you running with wide character argv values: 干编码,我不在Windows上开发,但使用TCLAP ,这应该让你运行宽字符argv值:

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

I personally would use stringstreams , here's some code to get you started: 我个人会使用stringstreams ,这里有一些代码可以帮助你入门:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM