setlocale的C++土耳其字符串问题
C++ Turkish string problem with setlocale
我想从用户的输入中找到土耳其语字符。这是我的代码:
#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;
行
相关文章:
- setlocale的C++土耳其字符串问题
- C++字符串问题-如何访问字符串元素
- 提升,从字符串问题中获得时间
- 字符串问题中的系统( "command" ) 字符串
- 从文件和字符串问题中读取
- 将C++函数转换为 C#(字符串问题)
- 有关字符串C++问题
- Visual Studio和Xcode之间的Chaiscript字符串问题
- 回文字符串问题:为什么我必须放+1而不是-1才能让这个代码工作
- Dll导入Marshal C++字符串问题
- 崩溃:字符串问题
- 正在寻找另一种解决二进制字符串问题的尝试
- C++ Win32 是字符串问题
- 迭代器字符串问题
- Python 3:Python/C API字符串问题
- 带有空格的C++字符串问题
- 有些字符串问题
- C++11 std::regex_replace()创建带有特定字符串问题的regexp
- Turbo C++的字符串问题
- 棘手的子字符串问题