3
I’m solving an exercise where I have to fill a vector like struct
, and one of the values is char
, for that I made a while
and was using a simple assignment with "=" but it wasn’t working, so I did it with strcpy
but every time I run the program it doesn’t open and lock.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct aluno{
char* name;
float nota1, nota2, media;
}aluno;
void resize (FILE *arq);
void fill (aluno *std, FILE * arq);
void menu (aluno* std, FILE *arq);
void consulta (aluno* std, FILE *arq);
int counter (FILE *arq);
int main(int argc, char * argv[]) {
FILE *arq;
if (argc != 2) {
printf("Erro de sintaxe: %s NOME_ARQUIVO\n", argv[0]);
return 1;
}
arq = fopen(argv[1], "r");
if (arq == NULL){
printf("Erro ao abrir arquivo.\n");
}
else {
resize (arq);
}
}
void resize (FILE * arq){
aluno* std;
int cont = counter (arq);
std = (aluno *) malloc(cont * sizeof(*std));
fill (std, arq);
}
void fill (aluno* std, FILE * arq){
char nome[15];
int i = 0;
float nota1, nota2;
fseek (arq , 0 , SEEK_SET);
while ((fscanf (arq, "%s %f %f", nome, ¬a1, ¬a2)) != EOF){
strcpy (std[i].name, nome);
std[i].nota1 = nota1;
std[i].nota2 = nota2;
std[i].media = (nota1+nota2)/2;
i++;
}
printf ("\n\n\n\nArquivo carregado!\n");
menu (std, arq);
}
void menu (aluno* std, FILE * arq){
int escolha;
do {
printf ("\n\n -- Catalogo: -- \n\n");
printf ("1 - Inserir dado no final \n");
printf ("2 - Inserir dado na posicao 'N' \n");
printf ("3 - Remover dado no final \n");
printf ("4 - Remover dado na posicao 'N' \n");
printf ("5 - Buscar dado\n");
printf ("\nDigite sua escolha: ");
scanf ("%d", &escolha);
switch (escolha){
case 1:
printf ("\nEscolha: 'Inserir dado no final!'");
break;
case 2:
printf ("\nEscolha: 'Inserir dado na posicao - N - !'");
break;
case 3:
printf ("\nEscolha: 'Remover dado no final!'");
break;
case 4:
printf ("\nEscolha: 'Inserir dado na posicao - N - !'");
break;
case 5:
printf ("\nEscolha: 'Buscar dado!'");
consulta (std, arq);
break;
default:
printf ("\nEscolha: 'Inserir dado no final'!");
break;
}
} while (1);
}
void consulta (aluno* std, FILE *arq){
int cont, i=0;
cont = counter (arq);
printf ("\n\n Consulta de Alunos \n\n");
printf ("Quantidade de registros: %d\n", cont);
while (i < cont){
printf ("O aluno %s possui: Nota 1: %.2f, Nota 2: %.2f, Media: %.2f\n", std[i].name, std[i].nota1, std[i].nota2, std[i].media);
i ++;
}
}
int counter (FILE * arq){
int contador = 0;
char nome[15];
float nota1, nota2;
fseek (arq , 0 , SEEK_SET);
while ((fscanf (arq, "%s %f %f", nome, ¬a1, ¬a2)) != EOF){
contador ++;
}
return contador;
}
The error in question is in the function fill
.
The file is formatted as follows: nome nota nota
.
Next tip: don’t post the entire code, just isolate the important code snippet for your question. It gets easier to answer and sometimes doing so gives you an idea of what might be causing the problem.
– Vitor De Mario