0

I have the following program that takes the first line from a file f1.txt and copies it to another file, f2.txt.

#include <fstream>
#include <string>

int main()
{
    std::basic_ifstream<char32_t> fin("f1.txt");
    std::basic_ofstream<char32_t> fout("f2.txt");
    std::u32string s;
    std::getline(fin, s);
    fout << s;
}

The problem is that it throws an exception:

terminate called after throwing an instance of 'std::bad_cast'                                                                                                                                               
  what():  std::bad_cast

The getline function seems to be the problem, because if I remove it, the problem goes away:

#include <fstream>
#include <string>

int main()
{
    std::basic_ifstream<char32_t> fin("f1.txt");
    std::basic_ofstream<char32_t> fout("f2.txt");
    std::u32string s = U"π";
    //std::getline(fin, s);
    fout << s;
}

I tried changing the locale, but it didn't help:

std::locale::global(std::locale("en-US.UTF-8"));

What is the problem?

DarkAtom
  • 2,589
  • 1
  • 11
  • 27
  • Is https://stackoverflow.com/questions/41315675/why-does-stdbasic-ifstreamchar16-t-not-work-in-c11 relevant? – KamilCuk May 04 '21 at 19:58
  • In a nutshell, the I/O streams simply don't natively support `char16_t` and `char32_t`, only `char` and `wchar_t`. – Remy Lebeau May 04 '21 at 20:34

0 Answers0