Search code examples
ccharasciiwchar-t

ASCII characters in C


I'm trying to save a character from the cyrillic alphabet in a char. When I take a string from the console it saves it in the char array successfully but just initializing it doesn't seem to work. I get "programName.exe has stopped working" when trying to run it.

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <Windows.h>
#include <stdlib.h>

void test(){
    char test = 'Я';
    printf("%s",test);
}

void main(){
    SetConsoleOutputCP(1251);
    SetConsoleCP(1251);
    test();
}


fgets ( books[booksCount].bookTitle, 80, stdin ); // this seems to be working ok with ascii.

I tried using wchar_t but I get the same results.


Solution

  • If you're using Russian Windows which uses Windows-1251 codepage by default, you can print the character encoded as a single byte using the old printf but you need to make sure that the source code uses the same cp1251 charset. Don't save as Unicode.

    But the preferred way should be using wprintf with wide char string

    void test() {
        wchar_t  test_char   = L'Я';
        wchar_t *test_string = L"АБВГ"; // or LPCWSTR test_string
        wprintf(L"%c\n%s", test_char, test_string);
    }
    

    This time you need to save the file as Unicode (UTF-8 or UTF-16)

    UTF-8 may be better, but it's trickier on Windows. Moreover if you use UTF-8 you cannot use a char to store Я because it needs more than 1 byte. You must use a char* instead

    Note that main must return int, not void, and the above fgets must be called from inside some function