[英]Parsing command line arguments in a unicode C++ application
如果应用程序是unicode,如何解析传递给应用程序的整数作为命令行参数?
Unicode应用程序有这样的主要:
int _tmain(int argc, _TCHAR* argv[])
argv [?]是一个wchar_t *。 这意味着我不能使用atoi。 如何将其转换为整数? stringstream是最好的选择吗?
如果你有一个TCHAR数组或指向它的开头的指针,你可以使用std::basic_istringstream
来处理它:
std::basic_istringstream<_TCHAR> ss(argv[x]);
int number;
ss >> number;
现在, number
是转换后的数字。 这将工作在ANSI模式(_TCHAR是typedef'ed到char
)和Unicode(_TCHAR是typedef`ed到wchar_t,如你所说)模式。
TCHAR是一种适用于ANSI和Unicode的字符类型。 查看MSDN文档(我假设您在Windows上),atoi和所有基本字符串函数(strcpy,strcmp等)都有TCHAR等价物。
atoi()的TCHAR等价是_ttoi()。 所以你可以这样写:
int value = _ttoi(argv[1]);
干编码,我不在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;
}
我个人会使用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.