Skip to content

Why gets does not work when I use it with scanf?

An answer to this question on Stack Overflow.

Question

When i use gets separately this works. But, when i use scanf in my program it does not work. Can anyone explain what I've missed?

#include <stdio.h>
#include <stdlib.h>
    
int main(){
    char a[]="computer";
    char b[]={'p','c','\0'};
    char c[30];
    char d[30];
    printf("a=%s,b=%s\n",a,b);
    printf("enter a word\n");
    scanf("%s",c);
    printf("%s",c);
    printf("enter a sentence\n");
    gets (d);
    printf("%s",d);
    return 0;
}

Answer

scanf removes whitespace automatically from before the datum it's trying to get. An exception to this is the character formats (primarily %c), which don't remove whitespace. However, scanf leaves whitespace after the datum. Therefore, you'll need a way to get rid of that. Use

getc(stdin);

you can then continue on your merry way. This page has more documentation on getc.