繁体   English   中英

C++, If...Else 带字符串和特殊字符

[英]C++, If...Else with strings and special characters

我试图创建一个简单的程序来帮助我的学生训练德语不规则动词,但我在处理特殊字符和 If 语句时遇到了问题。 基本上它不识别 ä ö ü 和 ß,因此 output 是 Else 语句 (¨Nicht Gut")。我该如何修复它?

#include <iostream>
#include <conio.h>
#include <locale.h>

using namespace std;


int main () {
   
   setlocale(LC_CTYPE, "German");
   string Antwort1;
   string Antwort2;
   string Antwort3;
   getline(cin, str);
   
   cout << str;

   cout << "Präsens von BEHALTEN (du)" << endl;
   cin >> Antwort1;
       
   if (Antwort1 == "behältst") {
       cout << "Gut!" << endl;
   }
   else {
       cout << "Nicht Gut" << endl;
   }
   
   cout << "Präsens von BEHALTEN (er/sie/es/man) " << endl;
   cin >> Antwort1;
       
   if (Antwort1 == "behält") {
       cout << "Gut!" << endl;
   }
   else {
       cout << "Nicht Gut" << endl;
   }

   return 0;   
}

我试过


if (Antwort1 == (LC_CTYPE, "German"),"behält")


但它会导致相反的效果。 然后我写的每个字符串都是有效的(“Gut”)。

我的答案适用于使用经典默认命令提示符的Windows 10 控制台(我还没有在 PowerShell 等其他系统上尝试过,也没有在 Linux 上尝试过这些实验)。

在我看来,截至今天(2022 年 2 月 23 日),Windows 10 的命令提示符和 VS2019 的 Microsoft C/C++ 运行时不支持 Unicode UTF-8 :例如,请参阅这篇显示 CRT 崩溃的博文尝试致电时:

_setmode(_fileno(stdout), _O_U8TEXT);

并使用std::cout打印 UTF-8 文本。

根据我的经验,您可以使用Unicode UTF-16使 Unicode 在 Windows 命令提示符中工作。 您仍然可以在 C++ 应用程序中使用 UTF-8,但您必须在 Windows 边界处在 UTF-8 和 UTF-16 之间进行转换。

我修改了您的代码以使用 Unicode UTF-16,代码在使用 Visual Studio 2019 编译并在 Windows 命令提示符内执行时似乎可以正常工作:

// Used for _setmode calls
#include <fcntl.h>
#include <io.h>
#include <stdio.h>

// Console I/O with Unicode UTF-16 wcin, wcout and wstring
#include <iostream>
#include <string>

using std::wcin;
using std::wcout;
using std::wstring;

int main() {
    // Enable Unicode UTF-16 console input/output
    _setmode(_fileno(stdout), _O_U16TEXT);
    _setmode(_fileno(stdin), _O_U16TEXT);

    wcout << L"Präsens von BEHALTEN (du) \n";
    wstring Antwort1;
    wcin >> Antwort1;

    if (Antwort1 == L"behältst") {
        wcout << L"Gut! \n";
    } else {
        wcout << L"Nicht Gut \n";
    }
}

请注意使用L"..."表示 UTF-16 字符串文字,并使用基于wchar_tstd::wcoutstd::wcinstd::wstring而不是基于charstd::cout , std::cinstd::string

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM