-2

Just testing some code; the following is supposed to run until I enter 'n'. But it stops after one round. Can anyone explain it, and help me implement what I want?

#include <stdio.h>
int main ()
{
  char another = 'y';
  int num;

  while ( another == 'y' )
    {
        printf ("Enter an number ");
        scanf ("%d", &num);
        printf ("square of %d is %d", num, num * num);         
        printf ("\nWant to enter another number y/n\n");
        scanf ("%c", &another);

    }

}

Thanks.

I really appreciate every one's comments. I did search online for GDB, and used it later. I have to say it made identifying the issue so much easier. Thanks so much.

user3326293
  • 817
  • 1
  • 14
  • 37
  • 3
    See [this question](https://stackoverflow.com/questions/13542055/how-to-do-scanf-for-single-char-in-c). – vaindil Mar 15 '16 at 13:37
  • 3
    Did it occur to you to use your debugger to check what had been read by the scanf, or even just to printf out its value, before posting on SO? – Martin James Mar 15 '16 at 13:41

2 Answers2

4

Add a space before %c

scanf (" %c", &another);

To eat the left out newline in the buffer after the previous scanf().


1) Use the standard definition of main()

int main(void) //if no command line arguments.

2) Do check the return value of scanf() (and other functions), to make sure that the values were read without any errors.

Haris
  • 12,120
  • 6
  • 43
  • 70
-1

Use

scanf (" %c", &another);
       ^^^^^

Also it is better to write

printf ("square of %d is %lld", num, ( long long int )num * num);
                         ^^^^        ^^^^^^^^^^^^^^^^^^^^        
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335