C++ 键入特殊字符并保存在文件中

C++ 键入特殊字符并保存在文件中,c++,windows,visual-c++,unicode,C++,Windows,Visual C++,Unicode,我想用一个纯文本文件保存用户的输入,以便以后在应用程序中读出。可能会出现德语和西班牙语的特殊符号。不幸的是,下面的代码没有在文件中正确保存符号。如何最好地解决这个问题 我在C中通过类似于.bin文件而不是.txt保存了这个问题,但是在C++中没有更好的解决方案吗? #include <string> #include <fstream> #include <iostream> int main() { std::string s = "abcöä

我想用一个纯文本文件保存用户的输入,以便以后在应用程序中读出。可能会出现德语和西班牙语的特殊符号。不幸的是,下面的代码没有在文件中正确保存符号。如何最好地解决这个问题

我在C中通过类似于.bin文件而不是.txt保存了这个问题,但是在C++中没有更好的解决方案吗?
#include <string>
#include <fstream>
#include <iostream>

int main() {


    std::string s = "abcöäüÑ"; //(alt + 165 for Ñ)
    std::ofstream ofs{ "test.txt" };
    ofs << s <<'\n';            //this works fine  "abcöäüÑ"


    std::string s2;
    std::cin >> s2;     //typeing in the app abcöäüÑ   (alt+165 for Ñ)
    // i use a windows system with a german keyboard setting

    ofs << s2 <<'\n';       //this doesn't it gets   "abc”„¥"
}
#包括
#包括
#包括
int main(){
std::string s=“abcöäüñ”//(alt+165表示ñ)
std::of流{“test.txt”};
ofs最简单的解决方案(已弃用)是使用德语的ANSI代码页:

setlocale(LC_ALL, "gr");
cout << "abcöäüÑ\n";

ofstream fout("ansi.txt");
fout << "abcöäüÑ\n";
setlocale(LC_ALL,“gr”);

您能解释一下为什么必须使用
\u setmode(\u fileno(stdout),\u O_U16TEXT);//wcout而不是cout\u setmode(\u fileno(stdin),\u O_U16TEXT);//wcin而不是cin auto loc=std::locale(std::locale(),new std::codevt\u utf16())
为什么它不能用std::wstring,std::wcout工作?我不知道控制台的内部工作原理,我认为您对这个解释不感兴趣。您可能会问“为什么默认情况下不能这样做?”原因是调用
\u setmode
后无法使用
std::cout
(除非您将模式重置回
\u O_TEXT
)有人决定不中断默认程序的
cout
wfstream
有点复杂,但这是因为它可以同时支持UTF8和UTF16。请参阅更新的答案。
#include <iostream>
#include <string>
#include <fstream>
#include <codecvt>
#include <io.h>
#include <fcntl.h>

int main() 
{
    _setmode(_fileno(stdout), _O_U16TEXT);//wcout instead of cout
    _setmode(_fileno(stdin), _O_U16TEXT); //wcin  instead of cin
    std::locale loc_utf16(std::locale(), new std::codecvt_utf16<wchar_t>);

    std::wofstream fout(L"utf16.txt", std::ios::binary);
    if(fout)
    {
        fout.imbue(loc_utf16);
        fout << L'\xFEFF'; //insert optional BOM for UTF16
        fout << L"abcöäüÑ ελληνική\r\n";
        fout.close();
    }

    std::wifstream fin(L"utf16.txt", std::ios::binary);
    if(fin)
    {
        fin.imbue(loc_utf16);
        fin.seekg(2, std::ios::beg); //skip optional BOM if it were added
        std::wstring ws;
        while(std::getline(fin, ws)) std::wcout << ws << std::endl;
        fin.close();
    }
    return 0;
}
std::wcout << "enter:";
std::wstring sw;
std::wcin >> sw;

std::locale loc_utf8(std::locale(), new std::codecvt_utf8<wchar_t>);
std::wofstream fout(L"utf8.txt", std::ios::binary);
if(fout)
{
    fout.imbue(loc_utf8);
    fout << sw << L"\r\n";
    fout << L"abcöäüÑ ελληνική\r\n";
}