Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
scanf(";%s";)存储字符串,即使在scanf(";%d";)之后使用它_C_Scanf - Fatal编程技术网

scanf(";%s";)存储字符串,即使在scanf(";%d";)之后使用它

scanf(";%s";)存储字符串,即使在scanf(";%d";)之后使用它,c,scanf,C,Scanf,因此我编写了这段代码(忽略缓冲区溢出问题,因为这只是一个简单的示例): #包括 内部主(空){ int n; chars[10]; printf(“输入一个数字:”); scanf(“%d”和“&n”); scanf(“%s”,s); printf(“%s”,s); 返回0; } 字符串不应该存储在数组中,因为输入缓冲区中应该有一个“\n”,因此应该终止scanf(“%s”,s),但事实并非如此。输出打印字符串。格式说明符%s跳过前导空格,即任何'\n',','\t',。。。将被忽略,s[0]

因此我编写了这段代码(忽略缓冲区溢出问题,因为这只是一个简单的示例):

#包括
内部主(空){
int n;
chars[10];
printf(“输入一个数字:”);
scanf(“%d”和“&n”);
scanf(“%s”,s);
printf(“%s”,s);
返回0;
}

字符串不应该存储在数组中,因为输入缓冲区中应该有一个“\n”,因此应该终止scanf(“%s”,s),但事实并非如此。输出打印字符串。

格式说明符
%s
跳过前导空格,即任何
'\n'
'
'\t'
,。。。将被忽略,
s[0]
将包含输入的第一个非空白

要演示一下
scanf
中的情况,请参见下面的示例,该示例使用了
scanf
%n”
-功能,该功能返回到目前为止已处理的字符数;我使用了
sscanf
,结果不依赖于用户输入。请注意,在读取字符串时,
scanf
处理的字符数多于结果中存储的字符数:

#include<stdio.h>
int main(void){
    int n;
    int pos;
    char s[10];
    const char* simulatedInput = "123\n     abcde";
    const char* inputPtr = simulatedInput;

    sscanf(inputPtr,"%d%n",&n,&pos);
    printf("sscanf on %s processed %d charaters; result n: %d\n", inputPtr, pos, n);

    inputPtr += pos;  // inputPtr will point at the position of '\n'
    sscanf(inputPtr,"%s%n",s,&pos);
    printf("sscanf on %s processed %d charaters; yet s as '%s' contains only %lu characters\n", inputPtr, pos, s, strlen(s));

    return 0;
}

@非常感谢。我不知道。通常,它只会给后续的
“%c”
格式说明符带来问题,它不会自动跳过前导空格,除非特别指示使用
“%c”
“…因为输入缓冲区中应该有一个“\n”…-你从哪里得到这个想法的
scanf
根本不关心
\n
。For
scanf
\n
只是另一个空格字符。@AnT scanf确实关心带有%c、%n和%s的空格[只是吹毛求疵:的POSIX规范在未标记为POSIX扩展的部分中指出,“空白”包括表单提要
'\f'
和垂直选项卡
'\v'
,以及空白、制表符和换行符。这不是主要问题;您很少遇到这两种情况。(“奇怪的是,C标准在默认(C)语言环境下将回车符
”\r“
添加到
isspace()
识别的字符列表中。C标准在没有列出字符的情况下说“空白”;这意味着“isspace()所说的是空白”。)
#include<stdio.h>
int main(void){
    int n;
    int pos;
    char s[10];
    const char* simulatedInput = "123\n     abcde";
    const char* inputPtr = simulatedInput;

    sscanf(inputPtr,"%d%n",&n,&pos);
    printf("sscanf on %s processed %d charaters; result n: %d\n", inputPtr, pos, n);

    inputPtr += pos;  // inputPtr will point at the position of '\n'
    sscanf(inputPtr,"%s%n",s,&pos);
    printf("sscanf on %s processed %d charaters; yet s as '%s' contains only %lu characters\n", inputPtr, pos, s, strlen(s));

    return 0;
}
sscanf on 123
     abcde processed 3 charaters; result n: 123
sscanf on 
     abcde processed 11 charaters; yet s as 'abcde' contains only 5 characters