我有这样一个文件:
1234 Homer 18.5
1223 Bart 25.5
9341 Lisa 30.0
3420 Marge 28.4
8730 Abram 26.7
1876 Barns 27.8
1342 Smiters 23.0
7654 Milhouse 29.7
如何获取每一行的第一部分(例如 1234 )? 我怎样才能得到每行的名称(例如 Homer )?
我在下面写了这段代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
char ch[25];
int i, num;
FILE *fp;
fp = fopen("studenti.txt","r"); // read mode
if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of numeri.txt file are :\n");
for(i = 0; i < 25; i++){
while( ( ch[i] = fgetc(fp) ) != EOF ){
if(!(ch[i] >= 'A' && ch[i] <= 'Z') && !( ch[i] >= 'a' && ch[i] <='z')){printf("%c",ch[i]);}
}}
fclose(fp);
return 0;
}
怎么做到的??
最佳答案
这就是 fscanf
函数的用途:
int n;
char name[25];
float x;
FILE* fp = ...
while (fscanf(fp, "%d%24s%f", &n, name, &x) == 3) {
// Do something with the data you just read:
printf("int=%d name='%s' float=%f\n", n, name, x);
}
以上几点需要注意的地方:
fscanf
返回它从文件中读取的项目数。返回 3 时继续调用fscanf
%24s
表示“长度最多为 24 个字符的字符串”。name
有25个字符,因为最后一个是空终止符int
和float
参数通过 & 符号传递给fscanf
,因为fscanf
需要一个指针。另一方面,String 不带和号,因为它等同于指针。
关于c - 如何从文件中获取 int - string - float?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27482496/