如何解决fscanf 只读取一些字符
我需要从 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 举报,一经查实,本站将立刻删除。