0

Hiya, I'm trying to make a small loop which presents an error when the user inputs something apart from a float and gives them another opportunity. Here's what I've got so far.

printf("Enter a value for x:   ");
while (scanf("%lf", &x_temp) != 1) {
    printf("ERROR: Input real number\n");
    printf("Enter a value for x:   ");
    scanf("%lf", &x_temp);
}

But this just runs through the loop without giving the user another chance to enter another number:

user@user-vm:~/Desktop/Exercise_0$ ./a.out 
Enter a value for x:   a
ERROR: Input real number
Enter a value for x:   ERROR: Input real number
Enter a value for x:   ERROR: Input real number
Enter a value for x:   ERROR: Input real number
Enter a value for x:   ERROR: Input real number
Enter a value for x:   ERROR: Input real number
Enter a value for x:   ERROR: Input real number
Enter a value for x:   ERROR: Input real number
Enter a value for x:   ERROR: Input real number

Anyone got any ideas? Cheers guys

3 Answers 3

1

Try this:

for (;;)
{
    printf("Enter a value for x:   ");
    if (scanf("%lf", &x_temp) == 1) 
        break;
    printf("ERROR: Input real number\n");
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works but you have to input the value twice for some reason hmmm Cheers
1

You're not using the return value of the second scanf call anywhere. So it's probably succeeding, but then you immediately do another scanf at the top of the loop, after the input has already been consumed.

Comments

0

I'm not sure what the behavior is, but it appears you have an extra scanf(). The one that is part of the while condition will repeat each time through the loop. I don't see a need for the second one at the bottom of the loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.