1
#include<stdio.h>
int main()
    {
        int i,l,*A;char C;
        A=(int*)malloc(5*4);
        for(i=0;i<5;i++)
            scanf("%d",A+i);
        scanf("%c",&C);
        scanf("%d",&l);
        printf("%d%c\n",l,C);

return 0;
}

Input: 5 4 3 3 9 r 1

I expect the output to be 1r. But I am getting the output as 21473443 84...i.e. garbage.

3 Answers3

4

In your example, %c reads the space before the r, and the subsequent scanf("%d") fails to read an integer (since it's presented with r 1).

To verify this, examine the return value of scanf(): it is the number of items successfully matched and stored, so the final scanf() will return zero.

P.S. In the malloc() (or anywhere else for that matter) you should not assume that sizeof(int) == 4.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

For %c conversion specifier, scanf does not omit whitespaces as it does for %d for example. You have to tell scanf to skip whitespaces and then read first non-whitespace character. Here's your fixed code.

#include<stdio.h>
#include <stdlib.h>
int main()
    {
        int i,l,*A;char C;
        A=malloc(5*sizeof(int));
        for(i=0;i<5;i++)
            scanf("%d",A+i);
        scanf(" %c",&C);
        //     ^ here
        scanf("%d",&l);
        printf("%d%c\n",l,C);
        free(A);  // remember to free what you've malloc'd

return 0;
}

Since you are asking how to verify return value from scanf, see prototype of scanf:

int scanf(const char *format, ...);

As you can see, it returns int. Man page says even more about return value:

RETURN VALUE
These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

This part I will leave for you to do it. I hope that it is now clear how to check scanf's return value.

macfij
  • 3,093
  • 1
  • 19
  • 24
0

(1)Give space before %c in scanf (i.e) scanf(" %c",&C);

(2)Scanf function return the number of input items successfully matched and assigned.

To check scanf return value,

void main
  {
    int a,b,c,d;
    a=scanf("%d%d%d",&b,&c,&d);
    printf("a=%d\n",a);//a=3
    a=scanf("%d",&b);
    printf("a=%d",a);//a=1
  }
Anbu.Sankar
  • 1,326
  • 8
  • 15