我通过这两个例子问我的问题,在第一个程序中,当我输入我的名字时它工作正常:
#include <stdio.h>
int main ()
{
char str [20];
while(1)
{
printf ("Enter your name: ");
scanf ("%19s",str);
printf ("Your name is %s\n",str);
}
return 0;
}
输出:
Enter your name: Reza
Your name is Reza
Enter your name:
但是在下面的程序中,结果并不像预期的那样:
#include <stdio.h>
int main ()
{
char str [20];
while(1)
{
printf ("Enter your name: ");
scanf ("name=%19s",str);
printf ("Your name is %s\n",str);
}
return 0;
}
当输入name=Reza时,程序重复打印输出:
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
Enter your name: Your name is Reza
...
您认为错误在哪里? 提前致谢
最佳答案
它通过对 man scanf
的简单引用来解释。在您的第一种情况下:
scanf ("%19s",str);
%s
转换说明符忽略前导空格,因此留在输入缓冲区 (stdin
) 中的 '\n'
被静默消耗。
在你的第二种情况下:
scanf ("name=%19s",str);
您格式化字符串正在寻找文字"name="
作为输入的一部分,因为'\n'
离开了在您之前的输入未被消耗后,匹配失败发生,因为您的输入实际上是 "\nname=..."
,字符提取在此时停止,留下一个字符在未读的输入缓冲区中 - 导致每个后续输入都出现相同的故障。
您可以解决在格式字符串的开头包含一个空格导致任何前导空格被消耗的问题:
scanf (" name=%19s",str);
现在你可以输入,例如:
name=Gary
name=Tom
...
(当然,如果用户为任何名称输入超过 19 个字符,或者如果一只猫不小心踩到键盘,您仍然会遇到无关字符问题)
您还必须检查所使用的每个输入函数的返回值,尤其是 scanf
。只需检查是否发生了预期的转化次数,例如
if (scanf (" name=%19s",str) != 1) {
fputs ("error: conversion failed.\n", stderr);
/* handle error */
}
关于c - 通过 scanf() 提取输入字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58425131/