0
I am doing a C program that aims to read a list of purchases stored in a text file and add the total value of the prices of the products. In each line of the file has, the product name, the quantity available and the unit price. I did all the code and compiled, but the program closes unexpectedly every time it arrives at the part of the code that reads and stores in vectors. Follows the code:
void main() {
char arqnome[30];
printf("\nDigite o nome da lista de compras\n");
scanf("%s", arqnome);
FILE *arq = fopen(arqnome, "r");
if (arq == NULL) { printf("\nErro ao abrir o arquivo\n"); exit(1); }
int linhas = 0;
int letras = 0;
char c;
while (!feof(arq))
{
c = fgetc(arq);
if (isdigit(c) == 0 && c != '\n' && c!= ' ') { letras++; }
else
{
if (c == '\n') { linhas++; }
}
printf("\n%d letras", letras);
printf("\n%d linhas", linhas);
}
char **nomeproduto = malloc(linhas * sizeof(char));
for (int i = 0; i < linhas; i++) {
nomeproduto[i] = malloc(sizeof(char) * 10);
}
int *quantida = (int*)malloc(linhas * sizeof(int));
int *preco = (int*)malloc(linhas * sizeof(int));
for (int clean = 0; clean < linhas; clean++) { quantida[clean] = 0; preco[clean] = 0; }
fclose(arq);
FILE *arq1 = fopen(arqnome, "r");
//int i = 0;
int j = 0;
for (int i = 0; i < linhas; i++)
{
fscanf(arq1, "%s", *(nomeproduto+j));
fscanf(arq1, "%d", quantida[j]);
fscanf(arq1, "%d", preco[j]);
j++;
}
int total = 0;
for (int k = 0; k < linhas; k++) {
total = total + preco[k];
}
printf("\nA soma dos preocos dos produtos eh %d", total);
printf("\n");
fclose(arq1);
system("pause");
}
system("pause")
? What logic do you want to use this?– Maury Developer
system("pause") is only for cmd not to close immediately after the execution of the program has finished. It is used in windows, since in linux the terminal does not close after running.
– Matheus10772
Thank you for the reply
– Maury Developer
Are you doing the
fscanf
wrong. They should stay like this:fscanf(arq1, "%s", nomeproduto[j]);fscanf(arq1, "%d", &quantida[j]);fscanf(arq1, "%d", &preco[j]);
– Isac
@Isac Cara... Thank you very much, I spent a while smashing my head trying to make it work, and the mistake was so simple, it made me want to hit me kkkkk Do what né kkkk I’m beginner in the world of programming and is catching that you learn.
– Matheus10772
@Isac publish your answer. To gain reputation.
– Maury Developer
@Matheus10772 is useless to use i
int j
where no for hasint i
– Maury Developer
Use like this:
for (int j = 0; j < linhas; j++)
 {
 fscanf(arq1, "%s", nomeproduto[j]);

 fscanf(arq1, "%d", quantida[j]);

 fscanf(arq1, "%d", preco[j]); 

 }
– Maury Developer