2017-08-07 79 views
1

这行代码工作正常。如何将字符串转换为u8?

#include <cstdlib> 
#include <iostream> 
#include <locale.h> 
#include <string> 
#include <locale> 
#include <codecvt> 
#include <cassert> 

int main() { 

    const auto str = u8"حخدذرزژس"; 
    wstring_convert<codecvt_utf8<char32_t>, char32_t> cv; 
    auto str32 = cv.from_bytes(str); 
    for (auto c : str32) 
     cout << uint_least32_t(c) << '\n'; 

    return 0; 
} 

我需要从文件中读取字符串“حخدذرزژس”。

如何初始化const auto str与从文件中读取的字符串以获得与上述代码相同的答案?

+0

@ OLIVER.KOO:他想从文件中读取 –

+6

'basic_string'不知道关于它的编码的任何信息。如果您的文件包含UTF8字符串,则只需从文件中读取它,就像读取任何其他字符串一样。 – Paul

+0

只是打开并阅读文件 –

回答

1

它حخدذرزژس

读取文件,并将其转换输入,如果是合法的UTF-8我创建了一个测试文件与下面的文本,

(注意:当您保存文本它应该是在U8格式)

#include<iostream> 
#include <fstream> 
#include <sstream> 
#include <string> 
#include <cstdint> 
#include <locale> 
#include <codecvt> 
using namespace std; 

std::wstring convert(const std::string& input) 
{ 
    try 
    { 
     std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; 
     return converter.from_bytes(input); 
    } 
    catch (std::range_error& e) 
    { 
     size_t length = input.length(); 
     std::wstring result; 
     result.reserve(length); 
     for (size_t i = 0; i < length; i++) 
     { 
      result.push_back(input[i] & 0xFF); 
     } 
     return result; 
    } 
} 
int main() 
{ 
    // read entire file into string 
    if (std::ifstream is{ "C:\\Users\\hsingh\\Documents\\Visual Studio 2017\\Projects\\ConsoleApplication4\\Debug\\test.txt", std::ios::binary | std::ios::ate }) { 
     auto size = is.tellg(); 
     std::string str(size, '\0'); // construct string to stream size 
     is.seekg(0); 
     if (is.read(&str[0], size)) 
     { 
      auto read = convert(str); 

     } 
    } 
} 

它读取文件

U8