unkown behaviour

This is a discussion on unkown behaviour within the C Programming forums, part of the General Programming Boards category; when i am running this code it is giving different behaviur with scanf("%c",&op) as mentioned in this code Code: #include<stdio.h> ...

  1. #1
    Registered User
    Join Date
    Feb 2008
    Location
    Bangalore, India
    Posts
    16

    Lightbulb unkown behaviour

    when i am running this code it is giving different behaviur with scanf("%c",&op) as mentioned in this code

    Code:
    #include<stdio.h>
    #include<conio.h>
    int main(void)
    {
    
    	int a,b;
    	char op;
    	
    	printf("Enter the number a and b");
    	scanf("%d\n%d",&a,&b);
        printf("Enter the opetration + or - ");
    	scanf("\n%c",&op); //it is working in this way
    //	scanf("%c",&op);  //not working with this statement
    	switch(op)
    	{
    	case '+': 
    		printf("Sum of the number=%d",a+b);
    		break;
    	case '-': 
    		printf("Diff of the number=%d ",a-b);
    		break;
    	default:
    		  printf("Wrong operation");
    	}
    	getch();
    	
    }

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    The newline in your format string for scanf tells scanf "skip any whitespace" [you could use a space in the same place"]. If you don't do that, it will accept the newline entered when terminating the 2 numbers [unless you know what the program will do and enter "2 3+" when it asks for the numbers, instead of when it asks for the operator].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Feb 2008
    Location
    Bangalore, India
    Posts
    16
    thanks matsp

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unexpected variable behaviour
    By Dondrei in forum C++ Programming
    Replies: 5
    Last Post: 02-23-2009, 11:11 PM
  2. cache behaviour
    By cyberfish in forum C++ Programming
    Replies: 10
    Last Post: 12-25-2008, 06:48 AM
  3. Replies: 16
    Last Post: 04-20-2008, 01:15 PM
  4. String overflow behaviour
    By Morgan in forum C Programming
    Replies: 15
    Last Post: 10-10-2003, 02:37 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21