hi everyone, i'm a beginner in c programming so i'm here to ask you some help
sorry for grammatical errors, i'm from brazil!
i've just made the code below:
the program reads a file that contains numbers and strings, formatted like this:Code:#include <stdio.h> #include <conio.h> #include <iostream> #define cab01 "Relatorio de alunos - Pagina " #define cab02 "Turma: " #define cab03 "RA\tNome\t\tMedia\tSituacao" using namespace std; main() { int ra, ct_lin, ct_pag; float n1, n2, n3, prova, media; char *turma, *nome; //char str[50]; const char *situacao; FILE *cad; cout << "Sistema de relatorios"; cout << "\n\n"; cout << "Insira a turma: "; gets(turma); if((cad=fopen(turma,"r"))==NULL) { cout << "\nO arquivo nao pode ser aberto!"; getch(); exit(1); } ct_lin = 1; ct_pag = 1; cout << "\n\n"; cout << cab01 << ct_pag << "\n"; cout << cab02 << turma; cout << "\n\n"; cout << cab03; cout << "\n\n"; while(!feof(cad)) { /* fgets(str, 50, cad); nome = strtok(NULL,","); ra = atoi(strtok(str,",")); n1 = atof(strtok(NULL,",")); n2 = atof(strtok(NULL,",")); n3 = atof(strtok(NULL,",")); prova = atof(strtok(NULL,",")); */ fscanf(cad, "%d,%[^,]%f,%f,%f,%f", &ra, &nome, &n1, &n2, &n3, &prova); media = n1 + n2 + n3 + prova; if (media >= 7) situacao = "Aprovado"; else if(media >= 4) situacao = "Exame"; else situacao = "Reprovado"; if (ct_lin > 10) { ct_lin = 1; ct_pag++; cout << "\n\n"; cout << cab01 << ct_pag << "\n"; cout << cab02 << turma; cout << "\n\n"; cout << cab03; cout << "\n\n"; } cout << ra << "\t"; cout << nome << "\t\t"; cout << media << "\t"; cout << situacao << "\n"; ct_lin++; } fclose(cad); getch(); }
9999999,Name One,1.0,0.5,1.0,7.0
9999999,Name Two,0.5,0.0,1.0,5.5
... ... ... ...
as you can see, the fields are separated by commas.
i'm having trouble to read the name (second field), i have tried using both fgets (to gets the entire line of the file and token it [i commented in code]) and fscanf (which i preffer) but there are different problems! in first case (fgets and strtok) sometimes i get segmentation fault while i'm debuggin, and when this error doesnt happen, the content of the variable *nome (that stores the name) changes. in example, it starts with "Name One" content, and then, "Name O" and so "A", simply. why this happens?
what should i do to have my program running? if i remove that field from file and from code, everything works..
the best i can get is read a unique character with fscanf (using %c).
thanks in advance!
best regards,
renato furlan



LinkBack URL
About LinkBacks



