Rezaeimh7
Rezaeimh7

Reputation: 1545

How to convert a string to u8?

This lines of code works fine.

#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;
}

I need to read the string "حخدذرزژس" from file.

How do i initialize const auto str with the string read from file to get the same answer as the above code?

Upvotes: 2

Views: 2615

Answers (1)

Hariom Singh
Hariom Singh

Reputation: 3632

I have created a test file with following text in it حخدذرزژس

Reads the file and It converts the input, if it is valid UTF-8,

(note when you save the text it should be in U8 format)

#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);

        }
    }
}

It reads the file

U8

Upvotes: 2

Related Questions