[英]scanf is not working as expected
我想從用戶年齡,性別(m / f),婚姻狀況(m / u)中輸入3個輸入。 我使用char數據類型來表示性別和婚姻狀況。 這是下面的代碼..
#include<stdio.h>
#include<conio.h>
main() {
int age;
char gender,marital_status;
printf("Enter your age: ");
scanf("%d",&age);
printf("Enter your gender (m/f): ");
scanf("%c",&gender);
printf("\nEnter your marital status (m/u): ");
scanf("%c",&marital_status);
}
年齡部分是核心工作,即從用戶那里獲取年齡並將其存儲到年齡。 但之后,兩個printf語句一下子顯示出來。 如何逐一顯示它們以作為性別和婚姻狀況從用戶輸入。
這是因為%c
接受了進入年齡時留下的'\\n'
符號。 你最好讀一個字符串,並取第一個字符,如下所示:
char buf[2];
printf("Enter your gender (m/f): ");
scanf("%1s", buf);
gender = buf[0];
printf("\nEnter your marital status (m/u): ");
scanf("%1s", buf);
marital_status = buf[0];
%s
格式說明符設置為忽略所有空格。 請注意格式說明符中%
之后的一個字符限制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.