2014-05-17 3 views
-1

그래서 파일을 읽고 구조체 CARRO의 필드에 넣는 것이 좋습니다.하나의 fscanf를 사용하여 파일에서 여러 문자열 읽기

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); 
    } 
+0

당신은뿐만 아니라 점점 잘못된 출력을 추가하십시오. – usr2564301

+0

내 나쁜 .. 그것은 CARRO dados [4700] – user3648469

+0

'while (...);':';'와'fscanf (fp, "% [^] ...'fscanf (fp, % [^] ...' – BLUEPIXY

답변

0

아래 코드의 주석을 참조하십시오 :

내가 사용하고 파일이 자동차의 목록입니다 특정 모델에 대한 정보를 포함하는 각 라인은 다음과 같은 형식을가집니다 :

#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); 
    } 
관련 문제