【问题标题】:wscanf(L"%[^\n]") is inputting garbagewscanf(L"%[^\n]") 正在输入垃圾
【发布时间】:2019-08-02 09:46:03
【问题描述】:

我正在使用宽字符在 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
  • 建议L"%[^\n]" --> L" %29l[^\n]"
  • @AnttiHaapala 回复:you cannot mix printf and wprintf --> 有趣的LSNED
  • @chux 好吧,你“可以”,但你似乎需要一直打电话给fwide……哦,不,你不能:D
  • @chux 它是脚注:“如果方向已经确定,那么fwide 不会改变它......”即你需要调用 freopen all时间……

标签: c widechar


【解决方案1】:

很多事情都错了。

  • 您不能在同一个文件中混合使用printfwprintf,包括stdout(除非您一直调用freopen 来更改流的方向...)
  • %l[^\n] 缺少 l
  • 空格是非字母数字的,所有与其他说明符“正常工作”的原因是字符串不包含空格...

固定代码:

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

【讨论】:

  • @chux ENOCOFFE ;)
  • 它起作用了,不知道你只需要替换“ls”中的 s 而不是整个东西,并且不将 printf 与 wprintf 混合。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-18
  • 2017-09-04
  • 1970-01-01
  • 1970-01-01
  • 2016-11-30
  • 1970-01-01
  • 2017-06-13
相关资源
最近更新 更多