Форум программистов, компьютерный форум, киберфорум
C++/CLI Windows Forms
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.84/25: Рейтинг темы: голосов - 25, средняя оценка - 4.84
0 / 0 / 0
Регистрация: 20.01.2017
Сообщений: 36

Проблема с кодировкой UTF8 в richtextbox->Text

16.10.2018, 12:35. Показов 5127. Ответов 6
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуете уважаемые форумчане, у меня проблема, не отображается кодировка русских букв в richtextbox->Text, дело в том что я написал программу которая загружает исходный код сайта и у меня русский текст в richtextbox->Text отображается в виде непонятных символов, предполагаю что у меня не поддерживается кодировка UTF-8, как решить эту проблему?
0
Лучшие ответы (1)
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
16.10.2018, 12:35
Ответы с готовыми решениями:

Доступ к полю Text в RichTextBox из другого класса
В форме есть richtextbox, создал интерфейс формы(public interface class IMainForm), передал в него мой richTextBox1 (static...

Как в richtextbox->Text настроить показ длинной строки?
Как настроить richtextbox->Text таким образом что бы он показывал очень длинную строку в маленьком окне и не переносил ее в новою строку,...

Как в richtextbox->Text удалить текст до и после определенного символа?
как мне в Visual C++ реализовать удаление текста до и после определенного символа из richtextbox->Text я нашел код который это делает...

6
Администратор
Эксперт .NET
 Аватар для OwenGlendower
18260 / 14185 / 5366
Регистрация: 17.03.2014
Сообщений: 28,871
Записей в блоге: 1
16.10.2018, 21:57
kodiak01, покажи код загрузки html. Скорее всего там ошибка.
0
0 / 0 / 0
Регистрация: 20.01.2017
Сообщений: 36
16.10.2018, 22:19  [ТС]
вот код программы,

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#include "curl/curl.h"
#include <string>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "curl/curl.h"
#include <fcntl.h>  
#include <io.h>
#include <string>      
#include <sstream>
 
#define CURL_STATICLIB
#pragma comment(lib,"curl/libcurl_a.lib")
#pragma comment(lib,"curl/libeay32.lib")
#pragma comment(lib,"curl/ssleay32.lib")
#pragma comment(lib,"curl/libssh2.lib")
#pragma comment(lib,"curl/zlib.lib")
 
using namespace std;
int writer(char *data, size_t size, size_t nmemb, string *buffer);
string curl_httpget(const string &url);
string iAddress;
string iSource;
 
string urllink;
 
string curl_httpget(const string &url)
{
    string buffer;
 
    CURL *curl;
    CURLcode result;
 
    curl = curl_easy_init();
 
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_USERAGENT, "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)");
        curl_easy_setopt(curl, CURLOPT_HEADER, 0);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
 
 
        //curl_easy_setopt(curl, CURLOPT_HTTPHEADER, "Content-Type: text/html; charset=UTF-8");
 
 
 
        result = curl_easy_perform(curl);//http get performed 
 
        curl_easy_cleanup(curl);//must cleanup 
 
                                //error codes: http://curl.haxx.se/libcurl/c/libcurl-errors.html 
        if (result == CURLE_OK)
        {
            return buffer;
        }
        //curl_easy_strerror was added in libcurl 7.12.0 
        //cerr << "error: " << result << " " << curl_easy_strerror(result) <<endl; 
        return "";
    }
 
    cerr << "error: could not initalize curl" << endl;
    return "";
}
 
int writer(char *data, size_t size, size_t nmemb, string *buffer)
{
    int result = 0;
    if (buffer != NULL)
    {
        buffer->append(data, size * nmemb);
        result = size * nmemb;
    }
    return result;
}
#pragma once
 
namespace hn {
 
    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;
 
    /// <summary>
    /// Сводка для MyForm
    /// </summary>
    public ref class MyForm : public System::Windows::Forms::Form
    {
    public:
        MyForm(void)
        {
            InitializeComponent();
            //
            //TODO: добавьте код конструктора
            //
        }
 
    protected:
        /// <summary>
        /// Освободить все используемые ресурсы.
        /// </summary>
        ~MyForm()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::Button^  button1;
    protected:
    private: System::Windows::Forms::TextBox^  textBox1;
    private: System::Windows::Forms::RichTextBox^  richTextBox1;
    private: System::Windows::Forms::Button^  button2;
    private: System::Windows::Forms::RichTextBox^  richTextBox2;
    private: System::Windows::Forms::Button^  button3;
 
    private:
        /// <summary>
        /// Обязательная переменная конструктора.
        /// </summary>
        System::ComponentModel::Container ^components;
 
#pragma region Windows Form Designer generated code
        /// <summary>
        /// Требуемый метод для поддержки конструктора — не изменяйте 
        /// содержимое этого метода с помощью редактора кода.
        /// </summary>
        void InitializeComponent(void)
        {
            this->button1 = (gcnew System::Windows::Forms::Button());
            this->textBox1 = (gcnew System::Windows::Forms::TextBox());
            this->richTextBox1 = (gcnew System::Windows::Forms::RichTextBox());
            this->button2 = (gcnew System::Windows::Forms::Button());
            this->richTextBox2 = (gcnew System::Windows::Forms::RichTextBox());
            this->button3 = (gcnew System::Windows::Forms::Button());
            this->SuspendLayout();
            // 
            // button1
            // 
            this->button1->Location = System::Drawing::Point(347, 0);
            this->button1->Name = L"button1";
            this->button1->Size = System::Drawing::Size(55, 20);
            this->button1->TabIndex = 0;
            this->button1->Text = L"button1";
            this->button1->UseVisualStyleBackColor = true;
            this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click);
            // 
            // textBox1
            // 
            this->textBox1->Location = System::Drawing::Point(0, 0);
            this->textBox1->Name = L"textBox1";
            this->textBox1->Size = System::Drawing::Size(341, 20);
            this->textBox1->TabIndex = 1;
            // 
            // richTextBox1
            // 
            this->richTextBox1->Location = System::Drawing::Point(0, 26);
            this->richTextBox1->Name = L"richTextBox1";
            this->richTextBox1->Size = System::Drawing::Size(589, 101);
            this->richTextBox1->TabIndex = 2;
            this->richTextBox1->Text = L"";
            // 
            // button2
            // 
            this->button2->Location = System::Drawing::Point(408, 0);
            this->button2->Name = L"button2";
            this->button2->Size = System::Drawing::Size(58, 20);
            this->button2->TabIndex = 3;
            this->button2->Text = L"button2";
            this->button2->UseVisualStyleBackColor = true;
            this->button2->Click += gcnew System::EventHandler(this, &MyForm::button2_Click);
            // 
            // richTextBox2
            // 
            this->richTextBox2->Location = System::Drawing::Point(0, 133);
            this->richTextBox2->Name = L"richTextBox2";
            this->richTextBox2->Size = System::Drawing::Size(589, 125);
            this->richTextBox2->TabIndex = 4;
            this->richTextBox2->Text = L"";
            // 
            // button3
            // 
            this->button3->Location = System::Drawing::Point(472, 0);
            this->button3->Name = L"button3";
            this->button3->Size = System::Drawing::Size(57, 20);
            this->button3->TabIndex = 5;
            this->button3->Text = L"button3";
            this->button3->UseVisualStyleBackColor = true;
            this->button3->Click += gcnew System::EventHandler(this, &MyForm::button3_Click);
            // 
            // MyForm
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(590, 259);
            this->Controls->Add(this->button3);
            this->Controls->Add(this->richTextBox2);
            this->Controls->Add(this->button2);
            this->Controls->Add(this->richTextBox1);
            this->Controls->Add(this->textBox1);
            this->Controls->Add(this->button1);
            this->Name = L"MyForm";
            this->Text = L"MyForm";
            this->ResumeLayout(false);
            this->PerformLayout();
 
        }
#pragma endregion
 
 
    private: System::Void MarshalString(System::String^ s, std::string& os)
    {
        using namespace System::Runtime::InteropServices;
        const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
        os = chars;
        Marshal::FreeHGlobal(IntPtr((void*)chars));
    }
 
 
    private: System::Void HuyashaString(System::String^ s, std::string& os)
    {
        using namespace System::Runtime::InteropServices;
        const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
        os = chars;
        Marshal::FreeHGlobal(IntPtr((void*)chars));
    }
 
 
 
    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
 
        System::String^ myAddress = textBox1->Text;
        HuyashaString(myAddress, iAddress);
 
        iSource = curl_httpget(iAddress);
        String^ mySource = gcnew String(iSource.c_str());
        richTextBox1->Text = mySource;
        //String^ mySource = 
        richTextBox1->SelectAll();
 
        //richTextBox1->SelectionFont = gcnew System::Drawing::Font("Arial Unicode MS", 16);
        //richTextBox1->SelectionFont = gcnew System::Text::Encoding::GetEncoding(1251);
        //richTextBox1->Text = IO::File::ReadAllText("test.txt", System::Text::Encoding::GetEncoding(1251));
        //richTextBox1->Text = IO::StreamReader::Read(System::Text::Encoding::GetEncoding(1251));
        //System::Text::Encoding^ richTextBox1 = System::Text::Encoding::GetEncoding(1251);
        //auto Writer = gcnew IO::StreamWriter(fileName, false, Coding);
        //richTextBox1->Text = 
 
    }
 
    private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
 
        //System::String^ coding;
        //System::Text::Encoding^ richTextBox1 = System::Text::Encoding::UTF8;
        //System::String^ coding;
        //richTextBox1->UTF8;
        //gcnew IO::StreamReader(coding, coding);
        //richTextBox1->SelectedText->ToInt32();
        //String^ enc = gcnew System::Text::Encoding::GetEncoding(1251);
        //richTextBox1->Text = coding;
        //coding = richTextBox1->Text;
 
 
        /*
        String^ s = richTextBox1->Text;
        StringBuilder^ sb = gcnew StringBuilder(s->Length);
        for (int i = 0; i < s->Length; ++i) {
            sb->AppendFormat("\u{0:D5}?", (int)s[i]);
        }
        String^ result = s->ToString();
        */
 
 
        //richTextBox1. = System::Text::Font("Arial Unicode MS", 16);
 
        //_setmode(_fileno(stdout), _O_U16TEXT);
        //wprintf(L"\x043a\x043e\x0448\x043a\x0430 \x65e5\x672c\x56fd\n");
        //return 0;
 
        
        //std::stringstream ss;
        //auto inttext = Convert::ToInt32(richTextBox1->Text);
        //std::string s = to_string(inttext);
        //String^ c = gcnew String(s);
        //std::string str = std::to_string(inttext);
        //ss << inttext;
        //std::string str = ss.str();
        //std::ostringstream ost;
        //ost << inttext;
        //std::string s_num = ost.str();
        //std::cout << s_num << std::endl;
        
        int a;
        //a = int.Parse(richTextBox1->Text);
        int n;
        System::String^ c = richTextBox1->Text;
        String^ dc = gcnew String(iSource.c_str());
        //std::string s_num = c;
        //s_num = richTextBox1->Text;
        //std::istringstream ist(s_num);
        //ist >> n;
        std::cout << n << std::endl;
        //return 0;
        //richTextBox2->Text = gcnew IO::TextWriter::Encoding();
 
 
    }
 
private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e) {
 
    /*
    System::String^ myAddress = richTextBox1->Text;
    HuyashaString(myAddress, iAddress);
 
    iSource = iAddress;
    String^ mySource = gcnew String(iSource.c_str());
 
    //String^ mySource = gcnew IO::TextReader:
    //Encoding^ encoding = Encoding::GetEncoding(1251);
 
    richTextBox2->Text = mySource;
    */
    /*
    System::String^ myAddress = textBox1->Text;
    HuyashaString(myAddress, iAddress);
 
    iSource = curl_httpget(iAddress);
    String^ mySource = gcnew String(iSource.c_str());
    richTextBox1->Text = mySource;
    */
    //array<Byte>^ asciiBytes = Encoding::Convert(utf8, ascii, utf8Bytes);
 
    //String^ str = mySource;
    //richTextBox2->Text += str;
 
    //richTextBox2->SelectedText = IO::TextReader::ToString(System::Text::Encoding::UTF8);
 
    String^ str;
    //str = System::Text::Encoding::GetEncoding(1251);
    richTextBox1->Text = str;
 
 
 
 
}
};
}
прописываю https://yandex.ru и нажимаю на button1 затем в richtextbox загружается код сайта, там где русские буквы - видны кракозяблы
Миниатюры
Проблема с кодировкой UTF8 в richtextbox->Text  
0
Администратор
Эксперт .NET
 Аватар для OwenGlendower
18260 / 14185 / 5366
Регистрация: 17.03.2014
Сообщений: 28,871
Записей в блоге: 1
16.10.2018, 22:33
kodiak01, я в curl не спец. Обязательно именно ее использовать? В .NET есть свои более удобные средства для работы с http. Например класс WebClient.
C++
1
2
3
4
5
6
7
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
    System::String^ myAddress = textBox1->Text;
    System::Net::WebClient^ webClient = gcnew WebClient();
    webClient->Encoding = System::Text::Encoding::UTF8;
    richTextBox1->Text = webClient->DownloadString(myAddress);  
    delete webClient;
}
1
0 / 0 / 0
Регистрация: 20.01.2017
Сообщений: 36
16.10.2018, 22:56  [ТС]
К сожалению мне нужно именно в curl.
Можете мне подсказать какой нибудь код Visual C++ который конвертирует текст из Ansi в utf-8, то есть из одного richtextbox1->Text в другой richtextbox2->Text таким образом что бы первом поле вводить такой текст "РќРѕРІРѕ" и во втором что бы уже выводился нормальный русский текст в utf-8?
0
 Аватар для Sklifosofsky
1085 / 915 / 213
Регистрация: 29.09.2015
Сообщений: 1,019
17.10.2018, 22:45
Лучший ответ Сообщение было отмечено kodiak01 как решение

Решение

Знакомая кракозябра
Попробуйте код ниже. Писал как-то для фикса клипбординга между DGV и Word. Почему-то на XP и .net системы разными таблицами кодировок пользовались
C++
1
2
3
4
    System::Text::Encoding ^win1251 = System::Text::Encoding::GetEncoding(1251);
    System::Text::Encoding ^utf8 = gcnew System::Text::UTF8Encoding(false, false);//System::Text::Encoding::UTF8;
    String ^outStr = utf8->GetString(win1251->GetBytes(this->richTextBox2->Text));
    richTextBox1->Text = outStr;
Я не знаком с curl, но может там есть установки кодировки выгружаемых данных?
1
0 / 0 / 0
Регистрация: 20.01.2017
Сообщений: 36
20.10.2018, 09:21  [ТС]
Sklifosofsky, Спасибо Большое, все работает
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
20.10.2018, 09:21
Помогаю со студенческими работами здесь

Как в richTextBox открыть файл с кодировкой UTF8
Создан проект с названием 1. в результате создается папка 1, папка Debug, файл 1 - тип файла VC++ Intellisense Database и 1 тип файла...

Проблема с кодировкой. response.setContentType('text/html;windows-1251')
Есть ASP-страница, общающаяся с БД на MSSQL-2000. Данные в большинстве полей - русско-язычные, напр. названия городов, стран и т.п. ...

Проблемы с кодировкой utf8
Делаю потихоньку сайт, возникла проблема некорректоного отображения на других компьютерах, конкретно в Fierfox. Мне сказали что нужно...

QT dll с кодировкой UTF8
Добрый день. Подскажите пожалуйста: существует ли где то в свободном доступе компилированные dll QT с кодировкой UTF 8, а не latin1? Я...

Трудности с кодировкой UTF8 в приложениях VS2017
Все проекты создаются с аброкадаброй... причем стандартные шаблоны создаются с кодировкой UTF8, а новые файлы в них - нет. Как решить эту...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Новые блоги и статьи
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит переходные токи и напряжения на элементах схемы. . . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru