Incorrect reading of floating point

0

I have a file that stores products, each product has three information: its name (char *), quantity in stock (int) and its price (float). The information generated in my program I am saving to a file and leaving the file in the following format:

quantidade-de-produtos
nome-produto-1
em-estoque-1 preco-1
nome-produto-2
em-estoque-2 preco-2
...

Example:

1
Refrigerante Xingu
50 3.500000 

Since I am writing the file, obviously I am also doing your reading, and this is where the problem is . I'm reading with the following code:

fscanf(dados, "%d ", &quantidade);
for (struct produto p; quantidade > 0; quantidade--){
    fscanf(dados, "%[^\n]*c", p.nome);
    fscanf(dados, "%d%f", &p.EmEstoque, &p.preco);
    ...

Once this is done, if I read in the example given above, it will read all the items correctly until the price is reached. The reading of the price should be 3,500,000, becomes only 3, and the .500000 is left out and the reading closed.

What's wrong with my code?

Product struct declaration if you need to better understand the code:

struct produto {
    char nome[100];
    int EmEstoque;
    float preco;
};
    
asked by anonymous 31.10.2018 / 18:48

3 answers

0

Problem solved.

The problem is not of reading, it is of writing. Reading a float to, when finding a '.', The correct character must be a ','.

    
31.10.2018 / 18:57
1

As you did not show all your code I wrote a small code that reads from a text file with the same formatting as your code reads.

file.c

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

int main(){
   FILE *fp;
   int qtd,estoque;
   char nome[100];
   float preco;

   fp = fopen("texto.txt", "r"); // read mode
   if (fp == NULL){
       perror("Error while opening the file.\n");
       exit(EXIT_FAILURE);
   }
   qtd=0;
   fscanf(fp, "%d ", &qtd);
   for (; qtd > 0; qtd--){
       fscanf(fp, "%[^\n]*c", nome);
       fscanf(fp, "%d %f", &estoque, &preco);
       printf("\n%s %d %f \n \n",nome,estoque,preco);
   }

   fclose(fp);
   return 0;
}

texto.txt

1
nome
5 3.5

program exit

nome 5 3.500000 

In this way, I can think that the problem in your code should be in one of the parts that you omitted, it is also worth mentioning that if you used some library or artifice to change the text formatting, it may require different entries like ' ' instead of '.' to float

    
31.10.2018 / 19:17
-1

Friend, using the "dot" in the directive, in your case "% .2f" instead of getting 3.500000 as you wish, would be a real value of 3.50, without the "dot" formatting in the directive, when printing will only come the value "int" of the given.

    
31.10.2018 / 19:06