为什么scanf()在处理字符串时不接受用户的输入?

时间:2011-11-17 12:19:20

标签: c input scanf

我的代码如下

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);

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

4 个答案:

答案 0 :(得分:3)

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

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

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

fgets总是从输入中获取一个完整的行,包括换行符(假设缓冲区足够大),从而避免了scanf所带来的问题。

答案 1 :(得分:1)

您可以为scanf使用字符串而不是字符。

答案 2 :(得分:1)

 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);

答案 3 :(得分:0)

尝试在 登录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;
} 
相关问题