tags:

views:

48

answers:

2

hello

i am having a trouble in taking input for the character type in c.the behavior of my source code is unusual.

my code is:

int n,i;
char *ps;

printf("Total no:");

scanf("%d",&n);

ps=(char *)calloc(n,sizeof(char));

for(i=0;i<n;i++) {
    printf("Enter character %d:",i+1);
    scanf("%c",ps+i);
}

then as per my requirement it should take input for all no. of n's but it's not working fine it will not take any input when the loop runs for the first time then it take input when loop runs 2 time and then in 4 time and so on.

so please tell me what's the error with my code?

-Thanks in advance.

+4  A: 

Each call to scanf inside the loop reads the next character. If you enter, for example:

Total no:4Enter

Then the first scanf will read 4 as an int, but the Enter will be seen by the next scanf (inside the loop) as a newline, \n.

Change the first call to scanf("%d\n", &n) and the one inside the loop to scanf("%c\n",ps+i).

larsmans
+1  A: 

Your scanf calls do not include the newline, so when you enter "5 [enter]" as input, the first scanf reads in the "5" and the second reads the newline. Try changing your scanf calls to look like scanf("%d\n", &n) or scanf("%d%*c", &n) to explicitly handle the newline.

bta