Can you accept comma and point to float in C?

Asked

Viewed 2,032 times

2

I would like to make an extremely simple program, but there is a problem that I would like to solve. Follow the code:

#include<stdio.h>

main(){
    float num;

    printf("Insira metros para converter para cm): \n");
    fflush(stdin);
    scanf("%f", &num);

    printf("%.2f\n", num*100);

system("pause");
}

If I don’t add the local library. h, for the user to enter a decimal number he will have to separate with point (.), and if I add it he will have to separate with comma (,). Is there any way my program will accept both comma and dot to separate decimals?

Thank you.

  • You read the input as string, swap (if any) the commas by dots, then convert the string (with dots) to floating comma value.

  • You can show me something to teach me that?

2 answers

1

The "right" way is to use a feature called "locale".

Example:

#include <locale.h>
#include <stdio.h>

int main(void)
{
  float num;

  setlocale(LC_NUMERIC, "pt_BR");

  printf("Insira metros para converter para cm: ");
  scanf("%f", &num);

  printf("%.2f\n", num);

  getchar();
}

Running on Linux:

[~/Projects/testes/so]
$ ./so373270 
Insira metros para converter para cm: 2,54
2,54...

[~/Projects/testes/so]
$

To work on Windows it seems that the locale is "en-BR" and not "pt_BR" as I used above, but I have not tested.

0


You can read the input as string, swap (if any) the commas for dots, then convert the string (with dots) to floating comma value

#include <stdlib.h> // strtod
#include <string.h> // strchr
double texttodouble(const char *p) {
    char *v = strchr(p, ','); // encontra a primeira virgula
    if (v) *v = '.';          // substitui por ponto
    return strtod(p, NULL);   // devolve double, assume locale "C"
}

See https://ideone.com/A2DpPC

Note that this code (and what is in ideone) has no validation of errors, and that this is necessary for a good program.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.