以下是读取输入、使用 以及如何使用正确格式字符串格式化输出的快速示例fopen()
:(fgets()
此处strtok()
显示的输出)
编辑显示将值放入 struct Alums
#include <ansi_c.h>
typedef struct alumnus { //Note "alumnus" is not necessary here, you have Alumns
int yearGraduated; //below that will satisfy naming the typedef struct
char firstName[30];
char lastName[30];
}Alumns;
Alumns a, *pA; //Create copy of struct Alumns to use
#define FILE_LOC "C:\\dev\\play\\file10.txt"
int main(void)
{
FILE *fp;
char *tok;
char input[80];
pA = &a; //initialize struct
fp = fopen(FILE_LOC, "r"); //open file (used #define, change path for your file)
fgets(input, 80, fp);
tok = strtok(input, ", \n"); //You can also call strtok in loop if number of items unknown
pA->yearGraduated= atoi(input); //convert this string in to integer
tok = strtok(NULL, ", \n");
strcpy(pA->firstName, tok); //copy next two strings into name variables
tok = strtok(NULL, ", \n");
strcpy(pA->lastName, tok);
//note the format strings here for int, and char *
printf("age:%d\n First Name: %s\n Last Name: %s\n",
pA->yearGraduated, pA->firstName, pA->lastName);
getchar(); //used so I can see output
fclose(fp);
return 0;
}