qua*_*ano 3 c++ unicode argv visual-c++
我在使用Visual Studio 2008时遇到了一些麻烦.非常简单的程序:打印作为参数发送的字符串.
为什么这样:
#include <iostream>
using namespace std;
int _tmain(int argc, char* argv[])
{
for (int c = 0; c < argc; c++)
{
cout << argv[c] << " ";
}
}
Run Code Online (Sandbox Code Playgroud)
对于这些论点:
program.exe testing one two three
Run Code Online (Sandbox Code Playgroud)
输出:
p t o t t
Run Code Online (Sandbox Code Playgroud)
?
我尝试用gcc做这个,然后我得到了整个字符串.
Ric*_*dle 19
默认情况下,_tmain将Unicode字符串作为参数,但cout期望ANSI字符串.这就是为什么它只打印每个字符串的第一个字符.
如果你想使用Unicode _tmain,你必须使用它TCHAR并wcout像这样:
int _tmain(int argc, TCHAR* argv[])
{
for (int c = 0; c < argc; c++)
{
wcout << argv[c] << " ";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您乐意使用ANSI字符串,请使用法线main,char并且cout像这样:
int main(int argc, char* argv[])
{
for (int c = 0; c < argc; c++)
{
cout << argv[c] << " ";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
更详细一点:TCHAR和_tmain可以是Unicode 或 ANSI,取决于编译器设置.如果定义了UNICODE,这是新项目的默认设置,则它们会说Unicode.UNICODE没有定义,他们说ANSI.所以从理论上讲,您可以编写不需要在Unicode和ANSI构建之间进行更改的代码 - 您可以在编译时选择所需的代码.
这下降的地方是cout(ANSI)和wcout(Unicode).没有_tcout或等同的.但你可以轻而易举地创建自己的并使用它:
#if defined(UNICODE)
#define _tcout wcout
#else
#define _tcout cout
#endif
int _tmain(int argc, TCHAR* argv[])
{
for (int c = 0; c < argc; c++)
{
_tcout << argv[c] << " ";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13558 次 |
| 最近记录: |