[英]How to read a file (.txt) with many columns skipping some of them, with scanf()
[英]skipping of some scanf in between
在此程序中,第二个和第四个scanf被跳过,不知道原因。 请问原因是什么?
#include<stdio.h>
main()
{
int age;
char sex,status,city;
printf("Enter the persons age \n");
scanf("\n%d",&age);
printf("enter the gender\n");
scanf("%c",&sex);
printf("enter the health status");
scanf("%c",&status);
printf("where the person stay city or village");
scanf("%c",&city);
if(((age>25)&&(age<35))&&(sex=='m')&&(status=='g')&&(city=='c'))
printf("42");
else if(age>25&&age<35&&sex=='f'&&status=='g'&&city=='c')
printf("31");
else if(age>25&&age<35&&sex=='m'&&status=='b'&&city=='v')
printf("60");
else
printf("no");
}
使用scanf()读取字符时,它将换行符留在输入缓冲区中。
变更:
scanf("%c",&sex);
printf("enter the health status");
scanf("%c",&status);
printf("where the person stay city or village");
scanf("%c",&city);
至:
scanf(" %c",&sex);
printf("enter the health status");
scanf(" %c",&status);
printf("where the person stay city or village");
scanf(" %c",&city);
请注意scanf格式字符串中的前导空白,它告诉scanf忽略空白。
另外,您可以使用getchar()来使用换行符。
scanf("%c",&sex);
getchar();
printf("enter the health status");
scanf("%c",&status);
getchar();
printf("where the person stay city or village");
scanf("%c",&city);
getchar();
我总是遇到与使用scanf
相同的问题,因此,我改用字符串。 我会用:
#include<stdio.h>
main()
{
int age;
char sex[3],status[3],city[3];
printf("Enter the persons age \n");
scanf("\n%d",&age);
printf("enter the gender\n");
gets(sex);
printf("enter the health status");
gets(status);
printf("where the person stay city or village");
gets(city);
if(((age>25)&&(age<35))&&(sex[0]=='m')&&(status[0]=='g')&&(city[0]=='c'))
printf("42");
else if(age>25&&age<35&&sex[0]=='f'&&status[0]=='g'&&city[0]=='c')
printf("31");
else if(age>25&&age<35&&sex[0]=='m'&&status[0]=='b'&&city[0]=='v')
printf("60");
else
printf("no");
}
如果第一个scanf
仍然给您带来问题(跳过第二个问题, gets
),则可以使用一些技巧,但是必须包括一个新库
#include<stdlib.h>
...
char age[4];
...
gets(age);
...
if(((atoi(age)>25)&&(atoi(age)<35))&&(sex[0]=='m')&&(status[0]=='g')&&(city[0]=='c'))
每次使用age
都要使用atoi
,因为atoi
会将char字符串转换为整数(int)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.