use wstring get line read file
Asked Answered
T

2

17

I have a file that contains text, I would like to get each line from this file into a std::wstring variable.If I do this I get an error, so is it possible to use std::wstring or I'm obligate to use a std::string ? This is my code :

std::ifstream fichier( "text.txt" );

if ( fichier )
{
  std::wstring ligne;

  while ( std::getline( fichier, ligne ) )
  {
      //work with ligne
  }
}

As mentioned, if I replace std::wstring by std::string I have no errors.

Tengler answered 19/11, 2015 at 14:26 Comment(0)
M
38

Try to use std::wifstream instead of std::ifstream

Mensurable answered 19/11, 2015 at 14:32 Comment(0)
B
0

To use wstring read file, I find wifstream works very good, even in visual studio debugger shows UTF-8 words correctly (I'm reading traditional chinese), from this answer:

#include <sstream>
#include <fstream>
#include <codecvt>

std::wstring readFile(const char* filename)
{
    std::wifstream wif(filename);
    wif.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t>));
    std::wstringstream wss;
    wss << wif.rdbuf();
    return wss.str();
}

//  usage
std::wstring wstr2;
wstr2 = readFile("C:\\yourUtf8File.txt");
wcout << wstr2;
Bale answered 15/4, 2021 at 15:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.