如何将用户从控制台的输入读取为 Unicode 字符串?

发布于 2024-09-09 06:33:34 字数 987 浏览 1 评论 0原文

一个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 条目限制为相同数量的字符。希望这样做相当简单和优雅。

A C++ beginner's question. Here is what I have currently:

// 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;

This happens to "work" in the US, but I have no idea what will happen if ... say a French user is running this app and starts to enter weird characters such as Çanemeplaîtpas.xml on command line. I am looking for a clean way to populate a string of the CAtlString type. The maximum length of the input can always be set long enough, but ideally I would like to limit the unicode, and non-unicode entries to the same number of characters. Hopefully doing so is reasonably easy and elegant.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风吹雨成花 2024-09-16 06:33:34

如果您期望 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;

}

Shouldn't you be using wcin stream if you expect unicode input?

#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;

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文