【问题标题】:C scanf not working for multi word inputC scanf不适用于多字输入
【发布时间】:2014-05-05 14:27:23
【问题描述】:

我有这个代码。

#include <stdio.h>
struct name
{
    int age;
    char fullname[20];
};

struct name names[20];

int main()
{
    int n,i;
    printf("Count of names:\n");
    scanf("%d",&n);
    for (i = 0; i < n; i++)
    {
        printf("Name %d : ",i);
        scanf("%[^\n]s",names[i].fullname);
    }
    return 0;
}

当我执行时:

rupam@linux ~ $ ./a.out 
Count of names:
5
Name 0 : Name 1 : Name 2 : Name 3 : Name 4 : 
rupam@linux ~ $

它不等待用户输入。不知何故,scanf 不起作用。

好吧,如果我使用

scanf("%s",names[i].fullname);

它适用于单字输入。 我在这里做错了什么?

【问题讨论】:

  • 去掉[^\n]
  • @BLUEPIXY:格式字符串的虚假s 是从哪里得到的?
  • @Deduplicator 啊!复制并粘贴。
  • @BLUEPIXY 谢谢,在%[^\n]s 工作之前添加一个空格。
  • 尝试scanf(" %[^\n]",names[i].fullname); :因为换行符剩余(scanf("%d",&amp;n);,)。

标签: c structure scanf


【解决方案1】:

让我们看看这里的输入会发生什么。首先,您调用scanf("%d" 来读取一个整数。假设您输入类似 5Enter 的内容,scanf 调用将读取数字并将它们转换为整数。因为它至少找到一个数字,所以它会成功,读取那个数字并将 Enter 中的 \n 留待读取。

现在进入循环,调用scanf("%[^\n]s",它尝试读取一个或多个非换行符,后跟一个换行符,然后尝试读取s。由于输入的下一个字符是换行符,这会立即失败(什么也不读),但是您没有检查scanf 的返回值,所以您不会注意到。然后您循环尝试阅读更多内容,这将再次失败。

所以你需要做的是忽略换行符。最简单的方法可能是只使用格式中的空格,这会导致scanf 读取并忽略空格,直到找到非空格字符;将您的第二个 scanf 更改为:

scanf(" %19[^\n]", names[i].fullname);

请注意此处的一些其他更改。我们去掉了虚假的s,因为您不想在名称后匹配s。我们还添加了 19 个字符的限制,以避免溢出 fullname 数组(最多 19 个字符 + 1 个用于终止 NULL 字节)。

【讨论】:

    【解决方案2】:

    在 for 循环中 printf 之后使用 getchar():

    #include <stdio.h>
    struct name
    {
        int age;
        char fullname[20];
    };
    
    struct name names[20];
    
    int main()
    {
        int n,i;
        printf("Count of names:\n");
        scanf("%d",&n);
        for (i = 0; i < n; i++)
        {
            printf("Name %d : ",i);
            getchar();//getchar here
            scanf("%[^\n]s",names[i].fullname);
        }
        return 0;
    }
    

    【讨论】:

    • 似乎不如只使用scanf 选项跳过空格。
    【解决方案3】:

    如果您将来可能使用带有 Windows 行尾的文件(将文件重定向到标准输入),那么您可以使用 @jahan 建议的而不是使用 getchar() 来代替

    if(getchar()=='\r') getchar();
    

    这可以增加代码的可移植性。

    【讨论】:

    • \r\n 在文件中将被转换为\n 在标准输入中,在 Windows 中。但是,放任自流也没有坏处。理想情况下继续阅读直到\nEOF 被点击。
    • @Matt McNabb 看完this question,我认为这不一定是真的。
    • 不认为什么是真的?
    • @Matt McNabb \r\n 将自动转换为 \n
    • 它是实现定义的,但我知道的所有 Windows 编译器都会这样做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多