Search code examples
cwidechar

wscanf(L"%[^\n]") is inputting garbage


I'm making a hangman program on c using wide characters. It has to allow spaces on the words to play (which the program will detect it as an illegal character).

The important part of the code:

int main(int argc, char** argv) {
    setlocale(LC_ALL, "");
    wchar_t sentence[30];
    printf("Gimme a sentence:\n");
    wscanf(L"%[^\n]", sentence); //Reading the line
    wprintf(L"Your sentence: %ls\n", sentence); //Printing the whole line

    printf("Detecting non-alphabetic wide characters"); //Detecting non-alphabetic characters
    for (int i = 0; i < wcslen(sentence); i++) {
        if (iswalpha(sentence[i]) == 0) {
            wprintf(L"\n\"%lc\" %i\n", sentence[i], i);
            printf("An illegal character has been detected here");
            return (1);
        }
    }
    return (0);
}

And the testing:

Gimme a sentence:
hello world
Your sentence: hello world
Detecting non-alphabetic wide characters
"o " 2
An illegal character has been detected here

I'm also suspecting that iswalpha() is messing up too, but when i change "%[^\n]" to "%ls", although it doesn't accept spaces, which i want the program to accept them. Is there any way for it to accept spaces and also not input garbage?


Solution

  • Many things wrong.

    • you cannot mix printf and wprintf on the same file, including stdout (except if you call freopen to change the orientation of the stream all the time...)
    • missing l for %l[^\n]
    • space is non-alphanumeric, that everything "worked" with the other specifier was due to the string not containing space...

    Fixed code:

    #include <locale.h>
    #include <stdio.h>
    #include <wchar.h>
    #include <wctype.h>
    
    int main(void) {
        setlocale(LC_ALL, "");
        wchar_t sentence[30];
        wprintf(L"Gimme a sentence:\n");
        wscanf(L"%l29[^\n]", sentence); //Reading the line
        wprintf(L"Your sentence: %ls\n", sentence); //Printing the whole line
    
        wprintf(L"Detecting non-alphabetic wide characters"); //Detecting non-alphabetic characters
        for (int i = 0; sentence[i]; i++) {
            if (iswalpha(sentence[i]) == 0) {
                wprintf(L"\n\"%lc\" %i\n", sentence[i], i);
                wprintf(L"An illegal character has been detected here");
                return 1;
            }
        }
        return 0;
    }