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.

Validating user input!!

+2 votes
asked Apr 6, 2023 by Zeyad Wael Ezzat (140 points)
I wrote a program that reads numbers from the user until the input equals "0" and prints the positive numbers and how many were they. But when I enter characters and press enter then enter zero it doesn't recognize the zero and keeps going. Here is the program I wrote:

#include <stdio.h>

int main()
{
    int x,count=0;
    float pos=0;
    printf("Enter the numbers: ");
    do
    {
        scanf("%d",&x);
        if (x>0)
        {
        pos=pos+x;
        count++;
        }
    }
    while(x!=0);
    
    printf("The positive values are %.1f \n",pos);
    printf("The positive values were repeated %d times",count);
    

    return 0;
}

1 Answer

0 votes
answered Apr 12, 2023 by Peter Minarik (88,520 points)

The problem is that when you enter an input that cannot be interpreted as a number, scanf() doesn't process it, but leaves it on the buffer. The next time your loop runs, actually it does not wait for any user input, it looks at the standard input again to see if there's a number there. But the old content is still there so you're going to process that for the rest of eternity and you're in an infinite loop.

You can check how many parameters scanf() has filled up with values. In your case, that's supposed to be 1 (x). If that's not the case, then you couldn't read a number and you should get rid of any leftover input from the standard input. Reading a string and throwing it away (asterisk format modifier "%*s") will do just fine.

Below is your code fixed with the above-suggested change, some variable and user interaction refactoring.

I hope this helps. Good luck! :)

#include <stdio.h>

int main()
{
    int x, count = 0;
    int sum = 0;
    printf("Enter the numbers (enter 0 to stop): ");
    do
    {
        if (scanf("%d", &x) == 1)
        {            
            if (x > 0)
            {
                sum += x;
                count++;
            }
        }
        else
        {
            scanf("%*s");
        }
    }
    while (x != 0);
    
    printf("The sum of positive numbers is %d.\n", sum);
    printf("%d positive numbers were entered.\n", count);

    return 0;
}
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.
...