gpt4 book ai didi

C 编程获取用户信息

转载 作者:行者123 更新时间:2023-11-30 17:22:07 26 4
gpt4 key购买 nike

这是我第一次使用 C 我需要询问用户一些信息才能输入

 #include <stdio.h>
#include <stdlib.h>

int main(void) {
int age;
int i;
char last_name[20];
char first_name[20];
double wight;
char gender[1];


printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your last name: ");
fgets(last_name, 18, stdin);
i = strlen(last_name)-1;
if( last_name[ i ] == '\n')
last_name[i] = '\0';

printf("Enter your first name: ");
fgets(first_name, 18, stdin);
i = strlen(first_name)-1;
if( first_name[ i ] == '\n')
first_name[i] = '\0';

printf("Enter your wight: ");
scanf("%lf", &wight);
printf("Enter your gender m/f: ");
gets(gender);

printf("You entered %s successfully\n ", first_name);
return EXIT_SUCCESS;
}

如果我运行该程序 输入您的年龄:23 输入您的姓氏: 输入您的名字:

我没有给我输入姓氏的机会 它跳到下一行

我使用的是eclipse ide

最佳答案

试试这个:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
int age;
int i;
char last_name[20];
char first_name[20];
double wight;
char gender[1];


printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your last name: ");
__fpurge ( stdin );
fgets(last_name, 18, stdin);
i = strlen(last_name)-1;
if( last_name[ i ] == '\n')
last_name[i] = '\0';

printf("Enter your first name: ");
fgets(first_name, 18, stdin);
i = strlen(first_name)-1;
if( first_name[ i ] == '\n')
first_name[i] = '\0';

printf("Enter your wight: ");
scanf("%lf", &wight);
printf("Enter your gender m/f: ");
__fpurge ( stdin );
gets(gender);

printf("You entered %s successfully\n ", first_name);
return EXIT_SUCCESS;
}

关于C 编程获取用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28103973/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com