Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Control of exceptions

+4 votes
asked Nov 10, 2020 by Vicent Cotaina Bertó (390 points)
I need to make that my code continues the execution when it takes a float number that conteins a "," instead of "."

But I dont know how to make it. Someone can help me?

1 Answer

0 votes
answered Nov 11, 2020 by Peter Minarik (84,180 points)

In many high-level languages there is support for globalization. (E.g. this one is for C#: https://docs.microsoft.com/en-us/dotnet/standard/globalization-localization/)

However, C does not have this kind of support.

C++ does. So if you're not limited to the use of C, but can use C++ as well, read this: https://stackoverflow.com/questions/15220861/how-can-i-set-the-decimal-separator-to-be-a-comma

If you really have to be oldschool C, then you have to write your own function.

What I'd do is probably something like read two integral numbers separated by comma. Then the first number will be the integral part while the second will be the fractional part.

#include <stdio.h>

double ReadDouble()
{
    int integral;
    int fractional;
    scanf("%d,%d", &integral, &fractional);
    double number = fractional;
    // TODO: Make sure the fractional part cannot be negative. Report an error if it is!
    // TODO: Make sure invalid input is not accespted. E.g. a,bc
    while (number > 1)
        number /= 10.0;
    number += integral;
    return number;
}

int main()
{
    printf("Enter a floating point number (e.g. 1,23): ");
    double d = ReadDouble();
    printf("\nYou entered: %lf\n", d);

    return 0;
}

Another alternative is that you read a whole line and start processing the line character by character.

Good luck! :)

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...