未知错误函数'scanf(“%[^ \ n]%* c”,&sent);'

要指出的是,我是C语言的初学者,只是在C程序中遇到了输入字符串的怪异方法:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    char ch,string[100],sent[100];
    scanf("%c",&ch);
    scanf("%s",&string);
    scanf("%[^\n]%*c",&sent);

    printf("%c\n",ch);
    printf("%s\n",string);
    printf("%s",sent);

    return 0;
}

这是错误:最后一行(句子)不打印,不知道我错了,但是在研究中我找到了以下代码:

scanf(" %[^\n]%*c",&sent); //not theres a space before %[^\n]%*c; and then it worked (wtf)

您能通过在其中添加一个空格来解释为什么它起作用吗?

shanghaiditu 回答:未知错误函数'scanf(“%[^ \ n]%* c”,&sent);'

格式字符串中的空格(todoList.objectID)导致scanf跳过输入中的空白。通常不需要它,因为大多数scanf转换在扫描任何内容之前也会跳过空格,但是两个%c不需要-因此在%[之前使用空格可以看到影响。让我们看看您的3个scanf调用做什么:

%[

因此,第3个scanf将开始读取以第二个scanf结尾的空白。如果您在格式的开头添加一个空格,它将读取并丢弃空白,直到找到一个非空白字符,然后开始使用该非空白字符读入scanf("%c",&ch); // read the next character into 'ch' scanf("%s",&string); // skip whitespace,then read non-whitespac characters // into 'string',stopping when the first whitespace after // some non-whitespace is reached (that last whitespace // will NOT be read,being left as the next character // of the input.) scanf("%[^\n]%*c",&sent); // read non-newline characters into 'sent',up until a // newline,then read and discard 1 character // (that newline)

如果第二个scanf结尾的空格恰好是换行符,将会发生什么呢?在这种情况下,三次scanf将完全失败(因为在换行符之前没有非换行符要读取),并且什么也不做。在第三个scanf中添加空格可确保它不会因换行而变坏(它将被替换为空格),因此,除非达到EOF,否则它将始终读取sent中的内容。

本文链接:https://www.f2er.com/3131736.html

大家都在问