我正在用宽字符在c上制作一个刽子手程序。它必须允许播放单词上的空格(程序会将其检测为非法字符)。
守则的重要部分是:

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);
}

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

我还怀疑iswalpha()也在搞乱,但是当我将“%[^\n]”更改为“%ls”时,虽然它不接受空格,但我希望程序接受它们。它有没有办法接受空间而不输入垃圾?

最佳答案

很多事情都错了。
不能在同一个文件上混合printfwprintf,包括stdout(除非您一直调用freopen来更改流的方向…)
l缺少%l[^\n]
空格是非字母数字的,与其他说明符一起“工作”的一切都是由于字符串不包含空格。。。
固定代码:

#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;
}

关于c - wscanf(L“%[^\n]”)输入垃圾,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55112697/

10-12 14:47