Ishan Khandelwal
Ishan Khandelwal

Reputation: 69

How to solve this infinite loop problem in C program I am facing?

I am getting an infinite loop for the program shown below when I run it twice without giving input for the first time. But when I give input on the first run then it is working perfectly.

But if I run it once and don't give input and rerun it, it results in an infinite loop.

How can I resolve the issue?

I am using VS Code.

Source code:

/*  UNIT CONVERSION
kms to miles
inches to foot
cms to inches
pound to kgs
inches to meters

*/
#include <stdio.h>
int main(int argc, char const *argv[])
{
    int x;
    float a;
start:
    printf("\nSelect the type of unit conversion you want\nkms to miles\tPRESS 1\ninches to foot\tPRESS 2\ncms to inches\tPRESS 3\npound to kgs\tPRESS 4\ninches to meters\tPRESS 5\nPRESS 0 TO EXIT\n");
    scanf("%d", &x);
    switch (x)
    {
    case 0:
        goto end;

    case 1:
        printf("Enter the value in Km to be converted into miles\n");
        scanf("%f", &a);
        printf("%f kms is %f miles\n", a, 0.621371 * a);
        goto start;

    case 2:
        printf("Enter the value in inches to be converted to foot\n");
        scanf("%f", &a);
        printf("%f inches is %f feet\n", a, 0.0833333 * a);
        goto start;

    case 3:
        printf("Enter the value in cms to be converted to inches\n");
        scanf("%f", &a);
        printf("%f cms is %f inches\n", a, a * 0.393701);
        goto start;

    case 4:
        printf("Enter the value in pound to be converted to kgs\n");
        scanf("%f", &a);
        printf("%f pound(s) is equal to %f kgs", a, a * 0.453592);
        goto start;

    case 5:
        printf("Enter the value in inches to be converted to metres\n");
        scanf("%f", &a);
        printf("%f inch(es) is equal to %f metre(s)", a, a * 0.0254);
        goto start;

    default:
        printf("You have not entered a valid input :(\n");
        goto start;
    }
end:
    printf("You have successfully exited the program\n");
    return 0;
}

Upvotes: 1

Views: 103

Answers (1)

koder
koder

Reputation: 2093

If you don't give any input, by which you probably mean you just hit enter, scanf fails and the x variable will not be set.

if (scanf("%d", &x) != 1) {
    x = -1;
}

This will set x to an invalid value in case no number was given. The code checks that scanf actually made exactly 1 conversion.

Always check scanf made the number of conversions requested.

And stop using goto. Use proper while, for, or do while loops.

Upvotes: 1

Related Questions