好吧,我整天都在做这个,我这辈子都写不下来,也许你们可以帮忙。我有一个文件,内容如下
1301,105515018,"Boatswain","Michael R.",ABC, 123,="R01"
1301,103993269,"Castille","Michael Jr",ABC, 123,="R03"
1301,103993267,"Castille","Janice",ABC, 123,="R03"
1301,104727546,"Bonczek","Claude",ABC, 123,="R01"
1301,104731479,"Cruz","Akeem Mike",ABC, 123,="R01"
1301,105415888,"Digiacomo","Stephen",ABC, 123,="R02"
1301,106034479,"Annitto Grassis","Susan",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 个整数。
获取姓氏字符串,因为它最多有 15 个字符,它会溢出到紧随其后的名字字符串中,并使用它需要的剩余字符来填充姓氏字符数组。显然我不想要这个。如您所见,我已经尝试过 strtok 但它没有做任何事情,不确定我必须做什么,因为我以前从未使用过它。也曾尝试将所有变量都包含到 fscanf 语句中,但我要么得到相同的输出,要么变得一团糟。事实上,我非常迷茫,如何将这些值放入它们所属的变量中?!
编辑:更新了我的代码,我走得更远但不多。我现在只能打印出姓氏,但不能打印出更远的名字,我无法获取名字字符串或超出它的任何变量。
最佳答案
您拥有的是一个带引号字符串的 CSV 文件,因此我建议您使用 CSV 解析器(或自己编写)而不是尝试使用 scanf
来完成所有操作(因为 scanf
无法处理引号,例如引号字符串中的逗号)。快速谷歌搜索出现libcsv.c您可以在您的项目中使用它。
关于c - 从文件 C 中的单行读取多个变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15149330/