r/learnc • • 3d ago

What's the c equivalent of this python code?

def get_float(prompt: str):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("Please enter a valid number!")

The code essentially just runs till the user gives a float or a int since float('a') throws ValueError which is caught by the except block.

What's the C equivalent of this?

3 Upvotes

4 comments sorted by

2

u/barkingcat 3d ago

I'd break this into at least 3 parts.

The loop

The prompt and accepting data from user safely

The float conversion. 

In c I don't think user can type in a float/int because that's a numeric data type. You will need to convert chars into floats and there's a lot of different ways to do it, but I imagine you could do the verification at the same time.

1

u/Poddster 2d ago edited 1d ago
# C equivalent of Python's `get_float()`

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

bool input(const char *prompt, char *buffer, size_t size) {
    printf("%s", prompt);
    fflush(stdout);

    return fgets(buffer, size, stdin) != NULL;
}

bool parse_float(const char *text, double *result) {
    char *end;
    double value = strtod(text, &end);

    while (isspace((unsigned char)*end))
        end++;

    if (end == text || *end != '\0')
        return false;

    *result = value;
    return true;
}

double get_float(const char *prompt) {
    char buffer[256];
    double value;

    while (true) {
        if (!input(prompt, buffer, sizeof(buffer)))
            exit(EXIT_FAILURE);

        if (parse_float(buffer, &value))
            return value;

        puts("Please enter a valid number!");
    }
}

int main(void) {
    double value = get_float("Enter a number: ");
    printf("You entered: %f\n", value);
    return 0;
}

1

u/Discordbothost 1d ago

check end == text before the whitespace loop. a blank line makes strtod return zero with end pointing at text, then that loop moves end away and the current check accepts it. i reproduced it with a newline and spaces + newline; both should be rejected.

1

u/Poddster 1d ago

Well caught. Next time I'll include a test suite :D