【问题标题】:How to read a user's input from the console into a Unicode string?如何将用户从控制台输入的内容读入 Unicode 字符串?
【发布时间】:2011-03-14 21:43:55
【问题描述】:

一个 C++ 初学者的问题。这是我目前拥有的:

// From tchar.h
#define _T(x)       __T(x)

...

// From tchar.h
#define __T(x)      L ## x

...

// In MySampleCode.h
#ifdef _UNICODE
    #define tcout wcout
#else
    #define tcout cout
#endif

...

// In MySampleCode.cpp
CAtlString strFileName;
if (bIsInteractiveMode)
{
char* cFileName = new char[513];
tcout << endl;
tcout << _T("Enter the path to a file that you would like to XYZ(purpose obfuscated) ") << endl;
tcout << _T(">>> ");            
cin.getline(cFileName, 512);
strFileName = cXmlFileName;
}

// Demonstrates how CAtlString can be printed using `tcout`.
tcout << _T("File named '") << strFileName.GetString() << _T("' does not exist.") << endl;

这在美国发生了“工作”,但我不知道如果......假设法国用户正在运行这个应用程序并开始在命令行上输入奇怪的字符,例如 Çanemeplaîtpas.xml,会发生什么。我正在寻找一种干净的方法来填充CAtlString 类型的字符串。输入的最大长度总是可以设置得足够长,但理想情况下,我想将 unicode 和非 unicode 条目限制为相同数量的字符。希望这样做相当简单和优雅。

【问题讨论】:

  • 这里有一个类似的问题:stackoverflow.com/questions/3207704
  • 真的,谢谢。但是,答案参考std::wstringstd::string。我想使用 ATL 字符串。
  • 与问题无关,我认为你应该像这样定义你的 cFileName: char* cFileName = new char[MAX_PATH];因为它是一条路径,所以你应该有 MAX_PATH imo

标签: c++ string unicode atl utf-16


【解决方案1】:

如果您期望 unicode 输入,您不应该使用 wcin 流吗?

#include <iostream>
#include <string>
#include <locale>

int main()
{
    using namespace std;

    std::locale::global(locale("en_US.utf8"));

    std::wstring s;

    std::wcin >> s;

    std::wcout << s;

}

【讨论】:

  • 请提供一个完整的代码示例 - 我会喜欢的!
猜你喜欢
  • 2011-08-10
  • 2011-11-08
  • 2013-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多