【问题标题】:Having trouble with char and scanf_s() [duplicate]char 和 scanf_s() 遇到问题 [重复]
【发布时间】:2013-11-26 10:26:16
【问题描述】:

我刚开始使用 C,但在编译时遇到了一些问题。 似乎编译器经常遇到 char 问题。 请注意我必须如何在 %c 之前放置空格。 现在在网上研究了一下后,我了解到在 &flag 之后添加 , 1 几乎可以解决这个问题,但我宁愿完全解决这个问题,因为它应该像这样正常工作。 我正在使用 Visual Studio 2013 顺便说一句。

#include <stdio.h>

void main()
{

  int num;
  char flag;
  while (1)
  {

    printf("Please enter your no.:");
    scanf_s("%d", &num);

    if (num > -1)
    {

      if (num < 10)
      {
        printf("Your number is 1 digit.\n");
      }

      else if (num < 100)
      {
        printf("Your number is 2 digits.\n");
      }

      else if (num < 1000)
      {
        printf("Your number is 3 digits.\n");

      }

      else if (num > 999)
      {
        printf("Your number has a lot of digits.\n");

      }
    }

    else
    {
      printf("Please input a correct value.\n");

    }

    printf("Would you like to countinue? y/n \n");
    scanf_s(" %c", &flag)
    // problem

    if (flag == 'n')
    {
      exit(0);
    }
  }

}

【问题讨论】:

    标签: c compiler-construction char


    【解决方案1】:

    您的代码无效,您必须使用scanf_s() 指定缓冲区大小。 See the documentation:

    scanfwscanf 不同,scanf_swscanf_s 需要为 c、C、s、S 或 [ 类型的所有输入参数指定缓冲区大小。以字符为单位的缓冲区大小作为附加参数传递,紧跟在指向缓冲区或变量的指针之后。

    这就是为什么如果您添加拨打电话scanf_s(" %c", &amp;flag, 1);,它会起作用的原因。

    【讨论】:

    • 并删除“%c”中的空格,即上面的“%C”。
    • 谢谢,解决了。但是我仍然需要在 %c 之前放置空格。
    • @VDN 在这种情况下需要格式字符串中的空格来消耗之前使用 scanf_s 在 while() 循环开始时读取 num 留在 stdin 中的换行符。跨度>
    • @Nigel Harper - 感谢您提供的信息。
    猜你喜欢
    • 2014-09-30
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 2016-07-15
    • 1970-01-01
    • 2014-01-02
    相关资源
    最近更新 更多