1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Arizona, USA
    Rep Power

    Scanf() in a while loop

    I'm not very fimilar with scanf() itself, usually I try to avoid it as it is not "stable"
    I was trying to do a simple addition with a for loop and then a while to ask the user to enter 'y' or 'n' to either repeat the program or terminate. My program seems to go into an infinite loop after I enter a character when prompted to repeat the program. I am sure the scanf() is what is causing the problem. I'm not sure how to fix it
    any suggesions?

    #include <stdio.h>
    int main ( void ){
      int sum, num, i;
      int again = 'y';
      while (again != 'n') {
        sum = 0;
        printf("\nEnter a positive integer: ");
        scanf("%d", &num);
        for (i = 0; i <= num; i++) sum += i;
        printf("The sum of %d integers is %d\n", num, sum);
        printf("\nWould you like to do it again (y/n)? ");
        scanf("%d", &again);
      return 0;
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Rep Power
    Do you realize what this line does?
    scanf("%d", &again);
    It scans the input for the next non-white space character expecting a digit and continues to read in digit characters until it reaches one that isn't a digit, where upon it converts that numeric string to an int value and stores it at the address you pass it.

    If you enter non-numeric input, such as 'n', then it will fail to convert that. scanf's return value is the number of successful conversions that it performed, which here should be 1 but if you enter 'n' it will be zero and the value of again will not have been changed.

    To make your program work as you want it to, you need to enter the ASCII value of 'n' rather than 'n'.

    To be able to accept 'n', you need to change again to char and you need to tell scanf to skip white space and read a single character; eg:
    scanf(" %c", &again);
    That space before the percent sign is extremely important; read my response in recent threads for the reason why.

IMN logo majestic logo threadwatch logo seochat tools logo