【问题标题】:Why doesn't scanf() take inputs from the user while dealing with strings?为什么 scanf() 在处理字符串时不接受用户的输入?
【发布时间】:2011-11-17 12:19:20
【问题描述】:

我的代码如下

typedef struct
{
 char name[15];
 char country[10];
}place_t;  

int main()
 {
 int d;
 char c;
 place_t place;
 printf("\nEnter the place name : ");
 scanf("%s",place.name);
 printf("\nEnter the coutry name : ");
 scanf("%s",place.country);
 printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?");
 scanf("%c",&c);
 printf("You entered %c",c);
 return 0;
 }

如果我运行程序,它会提示输入地名和国名,但从不等待用户输入的字符。
我试过了

fflush(stdin);
fflush(stdout);

都不行。

注意:如果我编写类似的代码来获取整数或浮点数,而不是字符,它会提示输入值并且代码可以正常工作。

int d;
printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?");
scanf("%d",&d);

为什么会这样?代码有什么问题吗?

【问题讨论】:

    标签: c input scanf


    【解决方案1】:

    问题在于scanf 在流缓冲区中输入的非空白字符之后留下空白,这是scanf(%c...) 然后读取的内容。不过等一下……

    除了难以正确处理之外,使用scanf 的代码非常不安全。最好使用fgets 并稍后解析字符串:

    char buf[256];
    fgets(buf, sizeof buf, stdin);
    // .. now parse buf
    

    fgets 总是从输入中获取整行,包括换行符(假设缓冲区足够大),因此您可以避免 scanf 遇到的问题。

    【讨论】:

      【解决方案2】:

      scanf 可以使用字符串代替字符。

      【讨论】:

        【解决方案3】:
         printf("\nEnter the place name : ");
         scanf("%s%*c",place.name);
         printf("\nEnter the coutry name : ");
         scanf("%s%*c",place.country);
         printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?");
         scanf("%c",&c);
         printf("You entered %c",c);
        

        【讨论】:

          【解决方案4】:

          尝试在 scanf() 中的 % 符号前添加空格。
          我在下面提供了修改后的代码。

          #include <stdio.h>
          #include <string.h>
          
          typedef struct
          {
              char name[15];
              char country[10];
          } place_t;
          
          int main()
          {
              int d;
              char c;
              place_t place;
              printf("\nEnter the place name : ");
              scanf(" %s",place.name);
              printf("\nEnter the coutry name : ");
              scanf(" %s",place.country);
              printf("\nEnter the type of the place : Metropolitan/Tourist (M/T)?");
              scanf(" %c",&c);
              printf("You entered %c",c);
              return 0;
          } 
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-10-24
            • 1970-01-01
            • 2011-01-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多