Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Runtime error occur?

Tags:

c

I am coding in Code-Blocks Editor with GNU GCC Compiler.I wrote the following code(including the relevant libraries and Header files)

int main()
{
char a;
scanf("%c",&a);
switch(a)
{
 case '1':
 scanf("%c",&a);
   if(a=='3')
    {
    printf("3\n");
    }else
    {
    printf("4\n");
    }


 break;

 case '2':
 printf("HELLO\n");
 break;

}



return 0;
}

When I ran the code,the terminal showed the cursor in order to get the character.I typed 1 and pressed return key.So it wanted me to enter another character.This time i typed 3 and pressed the return key again.Instead of printing 3 at the terminal something bad happened:a runtime error. Why did that happen?Which bad mistake did i made?Did i ignore some Scope Rules?if i did,which scope Rule did i ignore?

like image 404
Geralt Avatar asked Mar 02 '26 03:03

Geralt


1 Answers

Nothing wrong with the program. You only need to skip the '\n' character left behind by the previous scanf.
When you press Enter, then an extra character '\n' goes to the input buffer. This '\n' is left behind by the current scanf. On next read scanf will read this leftover character and you will get unexpected behavior of the program.

To skip this newline character you can place a space before %c

scanf(" %c",&a);  
  //   ^^ A space before %c can eat up any number of white spaces.  

Another way is to put this line after each scanf

int ch;
while((ch = getchar()) != EOF && ch != '\n');
like image 197
haccks Avatar answered Mar 03 '26 18:03

haccks