Показать полную графическую версию : Кирилица в консоли
Как сделать, чтобы консольные проги, написанные на С++, понимали русский... Я вообще новичок в программинге, можно по подробней??? Заранее спасибо!
from Xwine :locale.h тебе поможет
from Xwine
ну так открой "Дейтла и Дейтла" там подробно описано какие функции использовать и какие значения задавать .
YackoN
Есть такая функция в мастае CharToOem()
Поищи в WinAPI.
Перед выводом на консоль обработай строку этой функцией
Она конвертнет Win->Dos. И на экране все будет по русски а не по китайски. :)
А вообще-то где-то на этом форуме уже это было.
Удачи!
exdocent
31-12-2003, 18:06
YackoN
Если имеется в виду текст на русском языке, то нужно сделать следующее:
Во-первых нужно создать заголовочный файл
#include <windows.h>
Во-вторых сменить кодировку. Для этого в коде программы ввести
SetConsoleOutputCP(1251);
В-третьих настроить консоль. Для этого нужно щелкнуть правой кнопкой по верхней части консоли. В открывшемся меню выбрать "свойства", затем на вкладке "шрифт" выбрить Lucida Console
ezdefighter
16-12-2004, 10:20
Как сделать так, чтобы в консольных приложениях отображалась кириллица?
Можно использовать WinAPI функцию CharToOem():
CharToOem......Windows 95 Windows NT
Description
CharToOem translates a string from the character set of the current locale to an OEM-defined character set. If a character exists in the OEM character set, the character is used; otherwise, the nearest equivalent is selected.
Syntax
BOOL CharToOem( LPCTSTR lpszSource, LPSTR lpszDest )
Parameters
lpszSource
LPCTSTR: A pointer to a null-terminated string of the current character set.
lpszDest
LPSTR: A pointer to destination buffer to receive the OEM-based string. This buffer may be the same address as lpszSource, in which case the translation is performed in place. This cannot be done if using the wide-character version of this function.
Returns
BOOL: Always returns TRUE.
Include File
winuser.h
See Also
CharToOemBuff, OemToChar
Пример на C:
#include <windows.h>
#include <stdio.h>
void main()
{
char src[10];
char dest[10];
strcpy(src,"Привет");
CharToOem(src,dest);
printf(dest);
}
или же написать собственную процедуру перекодировки
Рискну предположить что такое прокатит:
uses Windows;
function Win2Oem (S: String) : String;
begin
CharToOem(PChar(S),PChar(Result));
end;
Простите, если такой вопрос уже был, но все-таки: как сделать чтобы Visual C++ 6.0 выводил нормальный русские буквы, а не "крякозяблы"?
Если Вы про консольный режим, то:
1. Откройте исходник
2. File -> Advanced Save Options -> Encoding -> Cyrillic (DOS) - Codepage 866
Правда у меня VS.NET, но я думаю, что эти же опции (или подобные) должны быть и у Вас ;)
Еще об одном способе узнал:
SetConsoleOutputCP
The SetConsoleOutputCP function sets the output code page used by the console associated with the calling process. A console uses its output code page to translate the character values written by the various output functions into the images displayed in the console window.
BOOL SetConsoleOutputCP(
UINT wCodePageID
);
Parameters
wCodePageID
[in] Identifier of the code page to set. The identifiers of the code pages available on the local computer are stored in the registry under the following key.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage
Return Values
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
A code page maps 256 character codes to individual characters. Different code pages include different special characters, typically customized for a language or a group of languages. If the current font is a fixed-pitch Unicode font, SetConsoleOutputCP changes the mapping of the character values into the glyph set of the font, rather than loading a separate font each time it is called. This affects how extended characters (ASCII value greater than 127) are displayed in a console window. However, if the current font is a raster font, SetConsoleOutputCP does not affect how extended characters are displayed.
To determine a console's current output code page, use the GetConsoleOutputCP function. To set and retrieve a console's input code page, use the SetConsoleCP and GetConsoleCP functions.
hasherfrog
26-01-2005, 22:52
Savant
Я только добавлю, что
Client: Included in Windows XP, Windows 2000 Professional, and Windows NT Workstation.
Server: Included in Windows Server 2003, Windows 2000 Server, and Windows NT Server.
Header: Declared in Wincon.h; include Windows.h.
Library: Use Kernel32.lib.
Обратите внимание, про Win 9x нет ни слова. Хотя они уже вымирают, конечно.
А вообще subj уже обсуждался, в подробностях, даже дважды, емнип...
Помогите плиз. Я считываю спомощю функции fopen, fread, fwrite с ASCII файла данные, но например в ShowMessage они отображаются как ANSI текст. И вот я никак немогу найти как зделать чтобы текст в переменой типа char или String перевести с ASCII в ANSI или с ANSI в ASCII.
а MSDN для кого ? http://msdn.microsoft.com (http://msdn.microsoft.com/)
CharToOem Function
The CharToOem function translates a string into the OEM-defined character set.
Syntax
BOOL CharToOem( LPCTSTR lpszSrc, LPSTR lpszDst);
Parameters
lpszSrc [in] Pointer to the null-terminated string to translate.
lpszDst [out] Pointer to the buffer for the translated string. If the CharToOem function is being used as an ANSI function, the string can be translated in place by setting the lpszDst parameter to the same address as the lpszSrc parameter. This cannot be done if CharToOem is being used as a wide-character function.
OemToChar Function
The OemToChar function translates a string from the OEM-defined character set into either an ANSI or a wide-character string.
Syntax
BOOL OemToChar(
LPCSTR lpszSrc, LPTSTR lpszDst);
Parameters
lpszSrc [in] Pointer to a null-terminated string of characters from the OEM-defined character set.
lpszDst [out] Pointer to the buffer for the translated string. If the OemToChar function is being used as an ANSI function, the string can be translated in place by setting the lpszDst parameter to the same address as the lpszSrc parameter. This cannot be done if OemToChar is being used as a wide-character function.
О спасибо тебе Старожил :) Не пойму как я не мог найти ету функцию в справке? Хотя искал все что связано с словом ОЕМ...
вот, очередной тупой вопрос !!! такая проблема:
#include <iostream>
using namespace std;
int main()
{
cout <<"привет";
return 0;
}
а в место привет, какие-то "закаручки" если в место привет, написать hello, то отобразится hello !!!!!!!!!!
sasha11
А вот у меня "привет" пишет! А почему? потому что вопрос кодировки ортогонален вопросу языка, а зависит только от среды. У меня всё в UTF8 - и текст программы, и кодировка в консоли. У вас же исходный текст в windows-1251 (а следовательно и слово "привет"), а стандартная кодировка в консоли windows - oem866 (досовская). Отсюда и все проблемы.
Есть как минимум 4 способа побороть эту проблему. Все они уже на этом форуме были перечислены не раз. Я уже говорил вам, что стоит пользоваться поиском прежде чем задавать вопросы? В следующий раз буду просто тупо закрывать тему.
Ссылки на существующие темы с тем же вопросом:
http://forum.oszone.net/showthread.php?t=64366
http://forum.oszone.net/showthread.php?t=30066
http://forum.oszone.net/showthread.php?t=29861
http://forum.oszone.net/showthread.php?t=42553
http://forum.oszone.net/showthread.php?t=47358
http://forum.oszone.net/showthread.php?t=44139
все понял, просто я в поиске ввел "кодировка в C++", "кодировка", и ничего нужного не нашел !!! в следующий раз буду делать более расширенные запросы(в поиске) !!!!!!
Учитывая, что архив с файлом автор удалил из своего сообщения (видимо из-за нехватки места), а скачивать неоткуда, было принято решение оформить шапку темы, в котором будет выложено содержимое заголовочного файла. ;)
Если кому надо, то могу кинуть билиотеку что бы после компиляции программы на Microsoft Visual C++ 6.0 она отображала шрифт кирилицы. Создать заголовочный файл russian.h Содержимое russian.h
#include <iostream.h>
#include <windows.h>
char* Rus(const char* text);
char bufRus[256];
char* Rus(const char* text)
{
CharToOem(text, bufRus);
return bufRus;
}Подключать
#include "russian.h"
Durson, а откомпилированая программа, если её запустить на другом компе, не потребует при запуске эту библиотеку?
© OSzone.net 2001-2012
vBulletin v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.