![](/img/trans.png)
[英]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.