gpt4 book ai didi

c - 打印c中的结构体值

转载 作者:行者123 更新时间:2023-11-30 19:25:44 25 4
gpt4 key购买 nike

我用c语言编写了一个小程序。该程序只是获取学生数据并将其保存在结构字段中。之后我希望打印数据,但代码似乎无法正常工作。

我是在 Visual Studio 17 IDE 中编写的。

#include <stdio.h>
#include <string.h>

struct Students
{
char Student_ID[12];
char Student_FirstName[20];
char Student_LastName[20];
char Student_StudyField[32];
int Student_Level;
};

int main()
{
struct Students STU1;

printf("Student ID: ");
scanf_s("%11s", STU1.Student_ID, sizeof(STU1.Student_ID));
printf("Student first name: ");
fgets(STU1.Student_FirstName, sizeof(STU1.Student_FirstName), stdin);
printf("Student last name: ");
fgets(STU1.Student_LastName, sizeof(STU1.Student_LastName), stdin);
printf("Student study field: ");
fgets(STU1.Student_StudyField, sizeof(STU1.Student_StudyField), stdin);
printf("Student level: ");
scanf_s("%2d", STU1.Student_Level, sizeof(STU1.Student_Level));

printf("\n");
printf("Student ID: %s\n", STU1.Student_ID);
printf("Student first name: %s\n", STU1.Student_FirstName);
printf("Student last name: %s\n", STU1.Student_LastName);
printf("Student study field: %s\n", STU1.Student_StudyField);
printf("Student level: %d\n", STU1.Student_Level);

return 0;
}

输出:

Student ID: 12345678900
Student first name: Tom
Student last name:
Student ID: 12345678900
Student first name: Tom
Student last name:

最佳答案

临时缓冲区 + gets + sscanf 应该可以工作

char buff[256] ;
STU1.Student_Level = 0 ; // Or other default
if ( fgets(buff, sizeof(buff), stdin) ) {
int v ;
if ( sscanf(buff, "%d", &v) == 1 ) {
STU1.Student_Level = v ;
} ;
} ;

关于c - 打印c中的结构体值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58437660/

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