setlocale的C++土耳其字符串问题

C++ Turkish string problem with setlocale

本文关键字:字符串 问题 土耳其 C++ setlocale      更新时间:2023-10-16

我想从用户的输入中找到土耳其语字符。这是我的代码:

#include <iostream>
#include <string>
using namespace std;
int main()
{
setlocale(LC_ALL, "Turkish");
string input;
string chars = "çığöşü";
cout << "Input: ";
getline(cin, input);
cout << "Turkish Characters: " << chars << "n";
cout << "Your input: " << input;
return 0;
}

当我运行它时,我会得到这个:

Input: çığöşü
Turkish Characters: çığöşü
Your input: ┼?§"Y?

如果我不使用setlocale,我得到的是:

Input: çığöşü
Turkish Characters: ²­÷■³
Your input: çığöşü

我使用了wstring,但它没有改变任何东西。我想从用户那里获得一些文本,并尝试使用我的字符串在文本中找到土耳其语字符。有简单的方法吗?(我使用的是Windows(

如果您的系统语言不是土耳其语,那么"çığöşü"将编译为英语或您拥有的任何设置,它将匹配为土耳其文的不同字符集。除非在编译器设置中将*.cpp文件的代码页更改为土耳其语。否则,您必须使用L"çığöşü"并将其转换为正确的ANSI代码页。

使用SetConsoleCP/SetConsoleOutputCP和代码页1254打印土耳其语。示例:

#include <iostream>
#include <string>
#include <windows.h>
std::string ansi(wchar_t* wbuf, int codepage)
{
int len = WideCharToMultiByte(codepage, 0, wbuf, -1, 0, 0, 0, 0);
std::string shortname;
shortname.resize(len, L'');
WideCharToMultiByte(codepage, 0, wbuf, -1, &shortname[0], len, 0, 0);
shortname.resize(len - 1);
return shortname;
}
int main()
{
int codepage = 1254;
SetConsoleOutputCP(codepage);
SetConsoleCP(codepage);
std::cout << ansi(L"çığöşün", codepage);
std::string input;
std::cout << "Input: ";
std::getline(std::cin, input);
std::cout << input << "n";
return 0;
}

建议使用Unicode(而不是使用visual Studio特定的_setmode(

#include <iostream>
#include <string>
#include <io.h> 
#include <fcntl.h> 
int main()
{
_setmode(_fileno(stdout), _O_U16TEXT);
_setmode(_fileno(stdin), _O_U16TEXT);
std::wcout << L"çığöşün";
std::wstring input;
std::wcout << "Input: ";
std::getline(std::wcin, input);
std::wcout << input << "n";
return 0;
}

试试这个函数:

string changeTrCharacters(string text){
replace (text.begin(),text.end(),-108,111); // ö to o
replace (text.begin(),text.end(),-103,79);  // Ö to O
replace (text.begin(),text.end(),-127,117); // ü to u
replace (text.begin(),text.end(),-102,85);  // Ü to U
replace (text.begin(),text.end(),-115,105); // ı to i
replace (text.begin(),text.end(),-104,73);  // İ to I
replace (text.begin(),text.end(),-89,103);  // ğ to g
replace (text.begin(),text.end(),-90,71);   // Ğ to G
replace (text.begin(),text.end(),-97,115);  // ş to s
replace (text.begin(),text.end(),-98,83);   // Ş to Ş
replace (text.begin(),text.end(),-121,99);  // ç to c
replace (text.begin(),text.end(),-128,67);  // Ç to C
return text;
}   

在主功能中,用cout << "Your input: " << changeTrCharacters(input);更改cout << "Your input: " << input;