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

13

如果一个应用程序是Unicode的,我该如何解析作为命令行参数传递给应用程序的整数?

Unicode应用程序有以下主函数:

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

argv[?] 是一个 wchar_t* 类型。这意味着我不能使用 atoi 函数。我应该如何将其转换为整数?stringstream 是最好的选择吗?

4个回答

6

如果您有一个TCHAR数组或指向其开头的指针,您可以使用std::basic_istringstream来处理它:

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

现在,number 是转换后的数字。这将在 ANSI 模式下工作(_TCHAR 被 typedef 为 char),以及 Unicode 模式下(_TCHAR 被 typedef 为 wchar_t)。

3

我没有在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;
}

2

TCHAR是一种字符类型,适用于ANSI和Unicode。在MSDN文档中查找(我假设您使用的是Windows),有atoi和所有基本字符串函数(strcpy、strcmp等)的TCHAR等效项。

atoi()的TCHAR等效项是_ttoi()。所以您可以这样写:

int value = _ttoi(argv[1]);

1

我个人会使用 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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接