c - 如何从文件中获取 int - string - float?

标签 c file char int

我有这样一个文件:

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个字符,因为最后一个是空终止符
  • intfloat 参数通过 & 符号传递给 fscanf,因为 fscanf 需要一个指针。另一方面,String 不带和号,因为它等同于指针。

关于c - 如何从文件中获取 int - string - float?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27482496/

相关文章:

c - 程序错误之间的字符串

C程序警告: format not a string literal and no format arguments

c - 将多个库静态链接成一个 .so

file -\x00 在二进制文件中是什么意思?

javascript - 如何在javascript中获取文件对象的所有属性?

java - 使用随机文件访问拆分文件不起作用

c# - ASCII 字符码

在 C 中使用 MPI 进行代码并行化

c - `static int (*const array[SIZE_ARRAY]...)(int a) = {[SOMETHING]=something}`在C中是什么意思?

c - strcpy() 中的段错误