0

Please give me a clear explanation for the below C program. It doesn't getting a character input after getting a string as an input .

This doesn't works

#include<stdio.h>
int main(){
    char name[25],alpha;
    printf("Enter your name \n");
    scanf("%s",name);
    printf("\nEnter a character \n");
    scanf("%c",&alpha);
    printf("\nyour name is %s, and you entered %c",name,alpha);
    return 0; 
}

This works

#include<stdio.h>
int main(){
    char name[25],alpha;
    printf("\nEnter a character \n");
    scanf("%c",&alpha);
    printf("Enter your name \n");
    scanf("%s",name);
    printf("\nyour name is %s, and you entered %c",name,alpha);
    return 0; 
}

why? what's the reason behind this execution. Thanks in advance

Mari Selvan
  • 171
  • 1
  • 7
  • See [How to read / parse input in C? The FAQ](http://stackoverflow.com/questions/35178520/how-to-read-parse-input-in-c-the-faq), the part called "When *scanf() does not work as expected". – Lundin Sep 13 '16 at 13:19
  • [doesn't work scanf char](http://stackoverflow.com/questions/29557448/c-program-doesnt-work-scanf-char) – BLUEPIXY Sep 13 '16 at 13:23
  • but I used same things for 2nd program as you saw in 1st program, its working in perfect way as it should. Then why 1st program doesn't works – Mari Selvan Sep 13 '16 at 13:28
  • @MariSelvan Read the accepted answer of the duplicate question. It tells you why you get the result you do and how to fix it. – Klas Lindbäck Sep 13 '16 at 13:36
  • That's fine @Klas Lindback . But can you give me a solution to scan and print a character after getting a string if possible . – Mari Selvan Sep 13 '16 at 13:51
  • @MariSelvan I did. Was anything unclear in the accepted answer to the linked queston? – Klas Lindbäck Sep 13 '16 at 14:17
  • Thanks @klas Lindback I'm too cleared . – Mari Selvan Sep 13 '16 at 19:32

0 Answers0