如何解析传递给应用程序的整数作为命令行参数,如果应用程序是unicode?解析unicode C++应用程序中的命令行参数
Unicode的应用程序有一个主这样的:
int _tmain(int argc, _TCHAR* argv[])
的argv是一个wchar_t的* [?]。这意味着我可以使用atoi。我怎样才能将其转换为整数?是串流最好的选择?
如何解析传递给应用程序的整数作为命令行参数,如果应用程序是unicode?解析unicode C++应用程序中的命令行参数
Unicode的应用程序有一个主这样的:
int _tmain(int argc, _TCHAR* argv[])
的argv是一个wchar_t的* [?]。这意味着我可以使用atoi。我怎样才能将其转换为整数?是串流最好的选择?
如果你有一个TCHAR数组或指针开始的话,你可以使用std::basic_istringstream
与它的工作:
std::basic_istringstream<_TCHAR> ss(argv[x]);
int number;
ss >> number;
现在,number
是转换后的数字。这将在ANSI模式下工作(_TCHAR的类型定义为char
),并且使用Unicode(_TCHAR按照您所说的模式定义为wchar_t)模式。
TCHAR是一种适用于ANSI和Unicode的字符类型。查看MSDN文档(我假设你在Windows上),有atocha和所有基本字符串函数(strcpy,strcmp等)的TCHAR等价物
atocha()的TCHAR等价物是_ttoi() 。所以,你可以这样写:
int value = _ttoi(argv[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;
}
}
干编码,我不能在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;
}
这听起来不太平台独立... – 2008-12-03 00:15:06