【问题标题】:Reading multiple strings from a file using one fscanf使用一个 fscanf 从文件中读取多个字符串
【发布时间】:2014-05-17 22:27:45
【问题描述】:

所以想法是读取一个文件并将其放入 struct CARRO 的字段中。

问题是,当我尝试 printf 一个结构变量(例如 dados[1].marca)时,它不会在控制台中显示任何内容。

我真的看不出问题出在哪里,因为 fscanf 实际上返回 8(8 个成功读取变量)。

我使用的文件是汽车列表,每一行都包含特定型号的信息,格式如下:

Ford[]Transit Custom Van 270L1 Econetic Base 2.2TDCi H1[\t]2013[\t]3[\t]2[\n]
(...)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
   {
   char marca[50]; 
   char modelo[50];
   char ano[5];
   char lugares[5];
   char portas[5];
   }CARRO;

main()
   {
   FILE *fp=NULL;
   CARRO dados[4700];
   int i=0;

   fp=fopen("car.txt","r");
   while (fscanf(fp,"%[^ ] %[^\t] %[^\t] %[^\t] %[^\n]", 
         dados[i].
         marca, 
         dados[i].modelo, 
         dados[i].ano,
         dados[i].lugares,
         dados[i].portas)!=EOF);  
      {
      i++;
      }

   fclose(fp);
   }

【问题讨论】:

  • 请同时添加错误的输出。
  • 我的错.. 是 CARRO dados[4700]
  • while(...); :删除 ;fscanf(fp,"%[^ ]... 更改为 fscanf(fp," %[^ ]...

标签: c file scanf


【解决方案1】:

见下面代码中的 cmets:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
   {
   char marca[50];
   char modelo[50];
   char ano[5];
   char lugares[5];
   char portas[5];
   } CARRO;

int main()     // Changed to 'int' type.
   {
   FILE *fp=NULL;
   CARRO dados[4700];
   int i=0;
   int nCnt;   // Added this line for printing result.

   fp=fopen("car.txt","r"); //Should check fp here to ensure file was successfully opened.  
   while(fscanf(fp," %[^ ] %[^\t] %[^\t] %[^\t] %[^\n]\n", // Slightly modified to 'gobble-up' newlines.
         dados[i].marca,
         dados[i].modelo,
         dados[i].ano,
         dados[i].lugares,
         dados[i].portas)!=EOF)  // Removed semicolon. As per 'BLUEPIXY'
      {
      i++;
      }
   fclose(fp);

   /* Added to print result. */
   for(nCnt = 0; nCnt < i; ++nCnt)
      printf("marca[%s] modelo[%s] ano[%s] lugares[%s] portas[%s]\n",
         dados[nCnt].marca,
         dados[nCnt].modelo,
         dados[nCnt].ano,
         dados[nCnt].lugares,
         dados[nCnt].portas
         );

   return(0);  
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 2014-02-10
    • 1970-01-01
    • 2023-03-17
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多