问题描述
我需要从 C 语言的 txt 文件中读取字符和整数的混合。文本文件有 1 行,内容如下:
Sarah (z) murphy 1 biology d 67
这意味着:
'name' 'initial' 'surname' 'year' 'course' 'group' 'average'
我的代码如下:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fptr = fopen("test1.txt","r"); // declare file pointer and open the file to 'read only'
//create variables to hold the values
char firstn[10],initial[3],secondn[10],course[10],group[1];
int year=0,average=0; //initialize at 0
// in case the file isn't found (returns NULL if it doesn't exist),exit the program
if(!fptr){
printf("File not found... Exiting program \n");
exit(1);
}
fscanf(fptr,"%s %s %s %d %s %s %d",firstn,initial,secondn,&year,course,group,&average); //read and assign to each variable
printf("here %s,%s,%d,%d \n",year,average); //print to show new variables
fclose(fptr); //close the file
return 0;
}
我不明白为什么不是每个变量都打印出来。我得到的结果是这样的:
,(z),murphy,1,d,67
我希望它看起来像:
Sarah,biology,67
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)