MathHopeful MathHopeful - 1 month ago 10
C Question

Stopping an infinite while loop using scanf in c?

I created a program that accepts 3 numbers separated by comments which I will use to do some calculations. It will accept user input for these numbers and I'm using scanf to accept that.

Here is what I have so far:

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

int main(void)
{
float a, b, c;

bool continue_program = true;

while (continue_program) {
printf("Enter your coordinates: ");
scanf("%f,%f,%f", &a,&b,&c);
if(isdigit(a) && isdigit(b) && isdigit(c)){
printf("Success!");
} else {
printf("Try again!");
}
}
}


Example Output:

Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!Enter your coordinates: Try again!


I know that other people have also faced the same issue and went through the answer for those ones but couldn't get their implementations working for this code.

Answer Source

You got it all wrong scanf() will return the number of arguments matched and you are not checking for that.

Also, the isdigit() function takes an integer, and returns non 0 if the ascii value of the passed argument corresponds to a digit.

To make your program stop when a condition is met, you should change the value of continue_program inside the loop, suppose you want to stop when scanf() didn't get 3 floating point numbers to read, it will return a value that is different from 3 so you can set that as the if condition

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

int main(void)
{
    float a, b, c;

    bool continue_program = true;

    while (continue_program) {
        printf("Enter your coordinates: ");
        if (scanf("%f,%f,%f", &a, &b, &c) == 3){
            printf("Success!");
        } else {
            continue_program = false;
            printf("Try again!");
        }
    }
}

This solution is suggested following the comments by the OP

#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>

int main(void)
{
    float a, b, c;
    char line[100];

    printf("Enter your coordinates: ");
    while (fgets(line, sizeof(line), stdin) != NULL) {
        size_t length;

        length = strlen(line);
        if (line[length - 1] == '\n')
            line[length - 1] = 0;
        if (strcmp(line, "0,0,0") == 0)
            break;
        if (sscanf(line, "%f,%f,%f", &a, &b, &c) == 3)
            printf("\tSuccess!\n");
        else
            printf("\tTry again!\n");
        printf("Enter your coordinates: ");
    }
}