[英]C LANGUAGE - How to read string, int and float from the same row of the same file.txt?
几周前,我开始在大学学习 C 语言。 我正在学习 C 语言,但我一直在从文件中读取内容:我会做一个例子。 假设我有一个名为 file,txt: 的文件,它包含:
Jack 7 8 7.5
John 5 6 5.5
我想在一个字符串中读取 Jack,在两个整数中读取 7 和 8,在浮点数中读取 7.5.. 第二行相同.. 我该怎么做?
int main(){
char file[15],name[15];
int a,b;
float c;
FILE* f;
scanf("%s",file);
f=fopen(file,"r");
if(f==NULL){
printf("Error reading file.");
return 1;
}
while(){
}
我现在该如何进行? 我不能做fscanf
因为它不会读取整行,如果我做fgets
,它将把所有行保存在一个字符串中,而字符串、整数和浮点数之间没有区别.. PS:抱歉英语不好,这是不是我的母语。
我将通过fscanf()
阅读它们。
#include <stdio.h>
int main(void){
char file[15],name[15];
int a,b;
float c;
FILE* f;
scanf("%s",file);
f=fopen(file,"r");
if(f==NULL){
printf("Error reading file.");
return 1;
}
while(fscanf(f, "%14s%d%d%f", name, &a, &b, &c) == 4){
/* do something */
}
fclose(f);
}
但是您说您不能这样做,因为fscanf()
不会读取整行(它将换行符留在输入缓冲区的行尾)。 然后,您可以使用fgets()
并使用sscanf()
来解析行。
#include <stdio.h>
int main(void){
char buffer[1024];
char file[15],name[15];
int a,b;
float c;
FILE* f;
scanf("%s",file);
f=fopen(file,"r");
if(f==NULL){
printf("Error reading file.");
return 1;
}
while(fgets(buffer, sizeof(buffer), f) != NULL){
if (sscanf(buffer, "%14s%d%d%f", name, &a, &b, &c) == 4) {
/* do something */
} else {
/* handle invalid line */
}
}
fclose(f);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.