Wednesday, 28 August 2013

Unpredictable Behaviour of scanf when used for reading input of Char type.

Unpredictable Behaviour of scanf when used for reading input of Char type.

I am learning linked lists, when I use scanf to input a character, the
code compiles fine but at run time it does not ask for input and skips the
scanf statement.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *ptr;
};
struct node* allocate();
struct node* create();
void display(struct node*);
int main()
{
struct node *new;
new=create();
display(new);
return 0;
}
struct node* allocate()
{
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
return temp;
}
struct node* create()
{
struct node *start,*next;
char ch;
start=next=allocate();
printf("Enter data:\n");
scanf("%d",&start->data);
perror("store data");
start->ptr=NULL;
R1: printf("Do you want to enter more data? y or n:: ");
scanf("%c", &ch); //Check for error here
if(ch=='y'||ch=='Y')
{
while(ch=='y'||ch=='Y')
{
next->ptr=allocate();
next=next->ptr;
printf("Enter data:\n");
scanf("%d",&next->data);
next->ptr=NULL;
printf("Do you want to enter more data? y or n:: ");
scanf(" %c",&ch);
}
}
if(ch=='n'||ch=='N')
{
return start;
}
else
{
printf("Please enter correct option.\n");
goto R1;
}
}
void display(struct node* temp)
{
printf("%d\n",temp->data);
while(temp->ptr!=NULL)
{
temp=temp->ptr;
printf("%d\n",temp->data);
}
}
Please Refer to the comment
Check for error here
in the code to know the statement i am referring to.
Now if i add a space before the the format specifier i.e. space before %c
in scanf statement then my code runs fine. .
scanf(" %c",&ch);
I face the same problem when I use getchar instead of scanf
ch=getchar();
when I run my code without using a space before the format specifier in
scanf statement or I use getchar() statement, my program does not ask for
input. It stores nothing in ch. Can anyone please explain me the reason
behind it? why does scanf behave so differently with character data types?
Additional info:
Using GCC
Linux Kernel 3.6.11-4
OS Fedora 16 (64 bit)
intel i5 processor.

No comments:

Post a Comment