2016-05-03 4 views
-1

Я пытаюсь сохранить .txt-файл в struct, не будучи успешным. Мне не нужна первая строка, но мне нужно все остальное. Спасибо, ребята! =)Сохранение .txt-файла в структуры

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

int main(int argc, const char * argv[]) { 
    // insert code here... 
    printf("Hello, World!\n"); 

    struct candidates 
    { 
     char name[25]; 
     char gender[5]; 
     int height; 
     int weight; 
    }; 

    struct candidates values[25]; 

    FILE *fp; 
    if ((fp=fopen("candidatesdata.txt","r"))==NULL){printf("Unable to open file\n");} 


    int x = 0; 
    int iterations = 0; 
    while((fscanf(fp,"%s,%s,%d,%d",&values[x].name, &values[x].gender, &values[x].height, &values[x].weight))!=EOF) 
     { 
      x++; 
      iterations +=1; 
     } 
    fclose(fp); 

    //values[15].weight = 300; 

    printf("\n%d\t%d",iterations,values[1].height); 


    return 0; 
} 

Текстовый файл выглядит следующим образом:

Name,Gender,Height,Weight 
Tanner,M,71.8,180.25 
John,M,70.75,185.3 
Parker,F,65.25,120.3 
Meeks,M,57.25,210.2 
+2

И ваша очередь stion/ошибка? – ckruczek

+5

ваш 'fscanf' ожидает целых чисел по высоте и весу, но они, очевидно, числа с плавающей точкой. – Aif

+0

неудивительно, но структура по-прежнему не сохраняет данные в txt вправо –

ответ

0
struct candidates 
    { 
     char name[25]; 
     char gender[5]; // can be char gender too !! 
     int height; // should be changed to float height 
     int weight; // should be changed to float height 
    }; 

Если вы фактически есть:

Name,Gender,Height,Weight 

в файле, вы можете сделать его, прежде чем идти на время цикла:

char somebigstring[100]; 
. 
. 
. 
if(fscanf(fp,"%s",somebigstring) == EOF) //wasting the first line 
    exit(-1); // exiting here if there is no first line 
+0

о, я вижу, я думаю, что смогу сделать цикл do/while –

0

Этот код выполняет две следующие вещи; сначала записывает данные в файл .txt, а второй считывает данные из TXT-файла и сохраняет в виде данных структуры, чего вы пытаетесь достичь, но только для одного объекта. Затем вы должны реализовать это как для сущностей.

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

typedef struct{ 
    char name[30]; 
    //other fields 
}Candidate; 

typedef struct{ 
    Candidate c; 
    char city[30]; 
    int vote; 
}CityVotes; 

//for .bin operations 
void write_to_file(FILE *f) 
{ 
    Candidate c; 
    CityVotes cv; 

    printf("Enter candidate name : "); 
    scanf("%s",&c.name); 
    cv.c = c; 
    printf("Enter the city : "); 
    scanf("%s",&cv.city); 
    printf("Enter the vote : "); 
    scanf("%d",&cv.vote); 
    fwrite(&cv, sizeof(cv), 1, f); 
} 
//for .txt operations 
void write_to_file1(FILE *f) 
{ 
    Candidate c; 
    CityVotes cv; 

    printf("Enter candidate name : "); 
    scanf("%s",c.name); 
    cv.c = c; 
    printf("Enter the city : "); 
    scanf("%s",&cv.city); 
    printf("Enter the vote : "); 
    scanf("%d",&cv.vote); 
    fprintf(f,"%s ", cv.c.name); 
    fprintf(f,"%s ", cv.city); 
    fprintf(f,"%d ", cv.vote); 
} 
//for .bin operations 
void read_file(FILE *f) 
{ 
    CityVotes cv; 
    while(fread(&cv, sizeof(cv), 1, f)){ 
     printf("Candidate : %s\t",cv.c.name); 
     printf("City.: %s\t",cv.city); 
     printf("Vote.: %d\n",cv.vote); 
    } 
} 
//for .txt operations 
void read_file1(FILE *f){ 
    CityVotes cv; 
    fscanf(f," %s", &cv.c.name); 
    fscanf(f," %s", &cv.city); 
    fscanf(f," %d", &cv.vote); 

    printf("Candidate : %s\t",cv.c.name); 
    printf("City.: %s\t",cv.city); 
    printf("Vote.: %d\n",cv.vote); 
} 
int main(void) 
{ 
    FILE *f; 
    f=fopen("candidates.txt","w"); 
    write_to_file1(f); 
    fclose(f); 
    f=fopen("candidates.txt","r"); 
    read_file1(f); 
    return 0; 
} 

Следует помнить, что код просто является примером, вы должны проверить наличие нулей.

+0

Никакое объяснение кода не могло привести к дальнейшему поиску например, почему существует структура «Кандидат», когда структура «CityVotes» может иметь только «char []». Этот ответ лучше подходит для комментариев с ссылкой на вопрос, на который вы ответили. –

+0

Правильно, вы можете избавиться от этой структуры и поместить char [] в CityVotes, но он или она может захотеть добавить к нему больше полей, что будет иметь смысл в структуре кандидата, но не в CityVotes. например, - пол, высота, возраст и т. д. –

0

исправить, как это:

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

struct candidates{ 
    char name[25]; 
    char gender[7];//Female+1 
    float height; 
    float weight; 
}; 

int main(void) { 
    struct candidates values[25]; 

    FILE *fp; 
    if ((fp=fopen("candidatesdata.txt","r"))==NULL){ 
     fprintf(stderr, "Unable to open file\n"); 
     exit(EXIT_FAILURE); 
    } 

    char line[64]; 
    int x = 0; 
    int iterations = 0; 
    while(fgets(line, sizeof line, fp)){ 
     iterations += 1; 
     if(x < 25 && sscanf(line, "%24[^,],%6[^,],%f,%f", values[x].name, values[x].gender, &values[x].height, &values[x].weight)==4){ 
      x++; 
     } else if(iterations != 1){ 
      fprintf(stderr, "invalid data in %d line: %s", iterations, line); 
     } 
    } 
    fclose(fp); 

    for(int i = 0; i < x; ++i){ 
     printf("%s,%c,%.2f,%.2f\n", values[i].name, *values[i].gender, values[i].height, values[i].weight); 
    } 

    return 0; 
} 
Смежные вопросы