about c programming

#include <stdio.h>
int main()
{
int a;
char b;
scanf("%d",&a);
scanf("%s",&b);
printf("%d",a);
printf("%c",b);
return 0;
}

when i give 1 and a as inputs why iam getting 0 and a ! as output need a reason

your program gives 0 and nothing as output because b is assigned ‘\n’ which is not visible in output .
try using this code , which gives correct output

#include< stdio.h >

int main()
{

int a;

char b[1];

scanf("%d",&a);

scanf("%s",b);

printf("%d\n",a);

printf("%s",b);

return 0;

}


Well, first of all u shouldn’t use %s placeholder to take a character as an input, use %c. Secondly, if u give input : 1 a into the program , it will store the ascii code of the " " character in b. Hence u can take input like this: scanf("%d %c",&a,&b);
This ignores the ’ ’ and stores the next value in the input into b.

Both the answer prevoiusly given are partially wrong.

You have two problems in the program.

  1. Always assign size of the character in use of char ( as it is assigned as arrays ), such as

                       char b[10];
    
  2. The char size must be greater than 1 here as one of the array is occupied by ‘\n’

    one more important thing, never use scanf("%c",&b), its wrong as b is a adress itself, you don’t have to reassign it. Thus it should be scanf("%c",b);

The correct program should be,

#include<stdio.h>

int main() {

int a;

char b[2];

scanf("%d",&a);

scanf("%s",b);

printf("\n%d\n",a);

printf("%s",b);

return 0;

}

@dheeru

#include <stdio.h>

int main()
{
    int a;
    char b;
    scanf("%d",&a);

    getchar();
    /* getchar() is used to consume '\n',
       left after integer input */

    /* If you will remove getchar() and test
       your code on input 1 a,
       Output will be 1 
       as '\n' is stored in b*/

    scanf("%c",&b);
    /* %c as format specifier to take a single
       character input from buffer */

    printf("%d ",a);
    printf("%c",b);
    return 0;
}
1 Like