NickAndNick

fstream I/O UTF-8

Sep 21st, 2019
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <string>
  5. using namespace std;
  6. bool writer(const wstring path, const vector<wstring>& content) {
  7.     wofstream stream(path);
  8.     stream.imbue(locale(".UTF-8"));
  9.     if (stream.is_open() && !stream.bad()) {
  10.         for (const auto& line : content) stream << line << L'\n';
  11.         stream.close();
  12.         return true;
  13.     }
  14.     return false;
  15. }
  16. vector<wstring> reader(const wstring path) {
  17.     vector<wstring> content;
  18.     wifstream stream(path);
  19.     stream.imbue(locale(".UTF-8"));
  20.     if (stream.is_open() && !stream.bad()) {
  21.         wstring line;
  22.         while (getline(stream, line)) content.emplace_back(line);
  23.         stream.close();
  24.     }
  25.     return content;
  26. }
  27. void test(wstring&& str) {
  28.     vector<wstring> content;
  29.     content.emplace_back(move(str));
  30.     wstring line;
  31.     wcout << L"Введите пару строк на русском языке:\n";
  32.     for (auto i = 0U; i < 2; ++i) {
  33.         getline(wcin, line);
  34.         content.emplace_back(line);
  35.     }
  36.     wcout.put(L'\n');
  37.     wstring path = LR"(D:\content.txt)";
  38.     if (writer(path, content)) {
  39.         auto result = reader(path);
  40.         if (result.empty()) wcout << L"Информация не найдена!\n";
  41.         else for (const auto& line : result) wcout << line << L'\n';
  42.     } else wcout << L"Ошибка записи в файл.\n";
  43. }
  44. int main() {
  45.     wcout.imbue(locale(".OCP"));
  46.     wcin.imbue(locale(".OCP"));
  47.     const wchar_t* message = L"Этот текст на русском языке:";
  48.     test(wstring(message));
  49.     wcout << LR"(Ура! Работает!
  50. Откройте в Notepad++ файл D:\content.txt)";
  51.     wcout.put(L'\n');
  52.     system("pause");
  53. }
Add Comment
Please, Sign In to add comment