【问题标题】:scanf() doesn't wait for string input in a loopscanf() 不等待循环中的字符串输入
【发布时间】:2021-04-24 14:41:37
【问题描述】:
#include <stdio.h>

int main()
{
    int i;
    for (i = 0; i < 4; i++)
    {
        printf("Enter the name of the player:\n");
        char* name;
        scanf(" %s", name);
    }

    return 0;
}

预期程序要求输入 4 次名称并让用户输入 4 个名称

输入:姓名

输出:

输入玩家姓名:

名字

输入玩家姓名:

输入玩家姓名:

输入玩家姓名:


如果你能帮我解决它,将非常感激

【问题讨论】:

  • 变量name是一个指针,但是它指向哪里?你需要一个数组来代替.
  • 该程序具有未定义的行为。 name 包含一些未初始化的地址,当您尝试使用它时可能会发生任何事情。将其替换为char name[1024];
  • 谢谢你们!这很有帮助。

标签: c loops scanf


【解决方案1】:

您不能将未分配的指针传递给“scanf”,因为“scanf”仅填充字符而不分配指针。

【讨论】:

    【解决方案2】:
    #include <stdio.h>
    
    int main()
    {
     int i;
     char name[100];
     for (i = 0; i < 4; i++)
     {
         printf("Enter the name of the player:\n");
         
         scanf(" %s", name);
     }
    
     return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-22
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      相关资源
      最近更新 更多