Issues with using scanf() to scan characters in loops in C

I've been a member of the question and answer site Stack Overflow for nearly a year now and there is one question that's always asked by beginners  in C language regarding scanning characters in a loop. Generally they would have a program like this:

 #include "stdlio.h"  
   
 int main(void)  
 {  
      char again = 'y'; //declaration and initialisation of a `char` variable
      //declarations of other variables...  
   
      //program....  
   
      //THE LOOP  
      while (again == 'y')  
      {  
           //looping statement.....  
   
           printf("want again? y/n : ");  
   
           //THE PROBLEM 
           scanf("%c", &again); //scanning the character  
      }  

      //rest of the program....

      return 0;  
 }  

and the question is why does the loop run only once even though they have entered input as `y` when prompted the message `want again?` while running the executable file. If you've done a fair bit of coding you might also have encountered such a problem.


Now what might be the problem?
Well if you recall while entering `y` as input, you didn't just press the `y` key but you also pressed the `enter` key. Now since `enter` key corresponds to the newline character i.e, `\n` in ASCII table, in the second iteration, it's consumed by the `scanf()` and so the program exits out of the loop as the condition ` again == 'y' ` is false because now, `again` equals to `\n` (newline character).

Here's a small program to prove that the `\n` character is scanned in the second iteration

 #include "stdio.h"  
 #include "conio.h"  
   
 int main(void)  
 {  
      int index = 1;    //to know the iteration number of the loop  
      char again = 'y';  //to store the character scanned  
      //other variables...  
   
     //TEST LOOP  
      for (; again == 'y'; index++)  
      {  
         //scanning the character  
           scanf("%c", &again);  
   
         //printing consumed character and it's corresponding ASCII value  
           printf("iteration number : %d || scanned character ASCII value : %d\n", index, (int)again);  
      }  
   
      printf("press any key to exit: ");

      getch(); //scan a character before exiting the program  
   
      return 0;  
 }  

Here in this program we are scanning a character and then before going to next iteration we are printing the iteration number and consumed character ASCII value by using the casting operation `(data-type)` on the character `again`. The output of above program is


This output would surely drive my point home. If you look at the ASCII values of scanned characters they are `121` and `10` respectively. If you look up the ASCII table (click here to see), the values of `newline` character is 10 and `y` is `121`. So I hope now you might understand why the loop is exited.


How to overcome the problem? 
The solution to the problem is quite simple, just provide a space before the format specifier in `scanf`statement this way:

 scanf(" %c", &again);  


Why provide the space before format specifier?
By giving a space, the compiler consumes the newline character and other white spaces such as '\n', '\0', '\t' and ' ' from the previous `scanf()` statement.

Now after providing the space in `scanf()` statement the output of the above program would be something like this:



I hope this gives a clear understanding about one of the most encountered beginner problem in C language.

Comments

Popular posts from this blog

Beginner's guide to Solving the N-Queens problem using backtracking method

PvP Chain reaction game using Python

Guide to Solving Maximal Subarray Problem using Kadane's Algorithm