c - 通过 scanf() 提取输入字符串的一部分

标签 c string scanf

我通过这两个例子问我的问题,在第一个程序中,当我输入我的名字时它工作正常:

#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/

相关文章:

c - scanf读取每一个双错

c - 为什么“while(!feof(file))”总是错误的?

c - 在结构体数组内分配结构体数组

c - c中的动态链接库找不到-lmean

javascript - 将颜色应用于字符串中的特定单词

C# 从字符串拆分中删除最后一个分隔字段

c - 使用 -O 标志编译时套接字代码失败

c++ - 字符串数据类型如何存储为字节

写入内存时 scanf C 中的 char[] 与 char*

c - 在 C 中,如何读取文件并仅存储 double - 之前忽略文本?