【问题标题】:Scanf doesn't work well with while loopScanf 不适用于 while 循环
【发布时间】:2016-10-30 11:19:20
【问题描述】:

所以我有以下代码:

void main(int argc, char **argv)
{
    int loggedIn=0;
    char *currentCommand;

    while (!loggedIn)
    {
    printf("Enter your command:");
    scanf("%s",currentCommand);
    printf("\n%s\n",currentCommand);
    }
}

问题是scanf() 第一次运行良好,然后开始读取(null),输出将是Enter your command: (null) 在无限循环中。

我想输入更多命令并在更改loggedIn的值时停止,但是一旦我输入一个命令,它就会开始打印Enter your command: (null) endlesly。

【问题讨论】:

  • 你还没有为currentCommand分配空间
  • 是的,现在可以使用了。谢谢!

标签: c console scanf


【解决方案1】:

您需要使用 ma​​lloccurrentCommand 指针分配内存(并在最后释放它)或在开始时为其指定大小,例如

char currentCommand[256];

【讨论】:

  • 现在工作。谢谢!
【解决方案2】:

currentCommand 是指针变量,它将保存 char 类型变量的地址(整数),大小为 4 字节(32 位机器)。

现在,当您在 scanf 中写入 ℅s 时,您应该传递 char 数组的地址。(您尚未声明),因此 scanf 将获取地址(保存在 currentCommand 中的值是垃圾)。

【讨论】:

    【解决方案3】:

    使用字符指针最重要的是你可以在声明时创建一个字符数组,即,

    char *p="Hello World";
    

    这会在只读部分的数据/代码部分中创建内存。

    您不能使用scanf() 函数创建字符数组。 应该必须使用动态内存分配或如上所述进行初始化

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 2015-08-09
      • 1970-01-01
      • 2017-06-28
      • 2020-02-16
      • 2012-06-25
      相关资源
      最近更新 更多