Click here to Skip to main content
15,069,133 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
int main()
    int num;
    char another;
        printf("enter the number");
        scanf("%d", &num);
        printf("the square is %d" ,num*num);
        printf("want another y/n");

    return 0;

What I have tried:

trying to copmile with do while loop but it just runs ones
Updated 3-Sep-21 21:53pm
Patrice T 4-Sep-21 2:46am
And you got an error message ?
Richard MacCutchan 4-Sep-21 4:59am
No, it's all down to the awful scanf.
Patrice T 4-Sep-21 5:06am
I know, I have seen other solutions, the OP said "trying to copmile".

scanf stops reading a number when it meets a non-digit character: so when you do this:
scanf("%d", &num);
printf("the square is %d" ,num*num);
the ENTER your user added to end the numeric value remains in the buffer.
And then you do this:
So it retrieves the next character and returns the ENTER instead of the user's next input.
To check that, run your code as is, and enter "123y" instead of "123" and press ENTER.

To fix the problem, write a function called ClearInputBuffer:
void ClearInputBuffer()
    int c;
    while ((c = getchar()) != '\n' && c != EOF) 
       { }
And call that after each time you read a "separate input" from the user to clear out the rest of the line.
Your problem is in this line
I'll let you figure it out from there.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900