【发布时间】:2012-01-16 03:33:56
【问题描述】:
几年前,我曾经用 C 进行一些基本的编程。现在我正在尝试重新学习我忘记的东西以及学习 Visual C++。我对所有字符串选项感到困惑,现在尝试使我的程序与 Unicode 兼容的额外层。我一直在阅读Beginning Visual C++ 2010 以及在线阅读以了解这些信息。
作为一个练习,我正在编写一个非常基本的程序,它要求用户输入一些文本,然后以消息框的形式显示该文本。该程序可以运行,但我让它运行的方式更多的是通过猜测和查看其他示例,而不是真正理解为什么我需要将各种字符串转换为不同的类型。
代码是:
#include "stdafx.h"
#include <iostream>
#include <string>
#include "Windows.h"
using std::wcin;
using std::wcout;
using std::wstring;
int _tmain(int argc, _TCHAR* argv[])
{
wstring myInput;
wcout << "Enter a string: ";
getline(wcin, myInput);
MessageBoxW(NULL, myInput.c_str(), _T("Test MessageBox"), 64);
return 0;
}
MessageBox 的语法是:
int WINAPI MessageBox(
__in_opt HWND hWnd,
__in_opt LPCTSTR lpText,
__in_opt LPCTSTR lpCaption,
__in UINT uType
);
另一方面,如果我只是使用命令行参数作为消息框的文本,我根本不需要转换字符串,我不知道为什么。
#include "stdafx.h"
#include <iostream>
#include <string>
#include "Windows.h"
using std::wcout;
int _tmain(int argc, _TCHAR* argv[])
{
MessageBoxW(NULL, argv[1], _T("Test MessageBox"), 64);
return 0;
}
我的困惑是:
为什么我需要将 c_str() 用于 MessageBoxW 的参数 2,为什么我需要在参数 3 中使用 _T() 宏 (?)?
为什么程序在没有进行某种转换的情况下在第二个代码示例中运行?
LPCTSTR 究竟是什么意思?我在 MSDN 函数中看到了另一个变体,称为 LPTSTR。
谢谢!
【问题讨论】:
-
看看this
-
谢谢!这确实很有帮助
标签: string visual-c++