好吧,我整天都在做这件事,我这辈子都无法理解,也许你们可以帮忙。我有一个文件,内容如下
1301,105515018,"水手长","迈克尔 R.",ABC, 123,="R01"
1301,103993269,"卡斯蒂利亚","小迈克尔",ABC, 123,="R03"
1301,103993267,"卡斯蒂利亚","珍妮丝",ABC, 123,="R03"
1301,104727546,"Bonczek","克劳德",ABC, 123,="R01"
1301,104731479,"克鲁兹","阿基姆迈克",ABC, 123,="R01"
1301,105415888,"Digiacomo","斯蒂芬",ABC, 123,="R02"
1301,106034479,"Annitto Grassis","苏珊",ABC, 123,="R04"
1301,106034459,"Als","Christian",ABC, 123,="R01"
这是我的代码...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME 15
#define MAX_SUBSEC 3
#define N 128
//void printArr(struct *students);
struct student{
int term;
int id;
char lastname[MAX_NAME];
char firstname[MAX_NAME];
char subjectname[MAX_SUBSEC];
int catalog;
char section[MAX_SUBSEC];
}students[10];
int main(){
int term;
int id;
char lastname[MAX_NAME];
char firstname[MAX_NAME];
char sub[MAX_SUBSEC];
int cat;
char sec[MAX_SUBSEC];
char fname[N];
FILE *inputf;
printf("Enter the name of the text file: ");
scanf("%123s",fname);
strcat(fname,".txt");
inputf = fopen(fname,"r");
if (inputf == NULL){
printf("I couldn't open the file for reading.\n");
exit(0);
}
//TROUBLE HERE!
fscanf(inputf, "%d,%d,%[^,]s", &students[0].term, &students[0].id,students[0].lastname);
printf("%d\n", students[0].term);
printf("%d\n", students[0].id);
printf("%s\n", students[0].lastname);
/*for (j = 1 ; j <= 10-1 ; j++){
for(k = 0 ; k <= 10-2 ; k++){
if(students[k] > students[k+1]){
temp = students[k];
students[k] = students[k+1];
students[k+1] = temp;
}
}
}*/
fclose(inputf);
system("pause");
return 0;
}
void printArr(int a[], int tally){
int i;
for(i = 0 ; i < tally ; i++){
printf("%d ", a[i]);
}
printf("\n");
}
我的目标是获取文本文件中的每个值并将其输入到它在结构中所属的位置,然后输入到结构数组中,但我无法通过前 2 个整数。
获取 lastname 字符串,因为它最多为 15 个字符,它会溢出到它之后的名字字符串,并获取它需要的剩余字符以填充 lastname char 数组。显然我不想要这个。如您所见,我尝试过 strtok 但它没有做任何事情,但不确定我必须做什么,因为我以前从未使用过它。也尝试过将所有变量都包含到 fscanf 语句中,但我要么得到相同的输出,要么变得一团糟。实际上,我非常迷茫,如何将这些值放入它们所属的变量中?!
编辑:更新了我的代码,我已经走得更远了,但不多。我现在可以只打印出姓氏,但不能更远,我无法得到名字字符串或超出它的任何变量。