vs06 vs06 - 1 month ago 18
C Question

scanf reading "Enter" key

Why scanf doesn't work when I type "Enter" in the code below?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char**argv)
{
char *msg = malloc(100*sizeof(char));
do{
scanf("%s",msg);
printf("%s\n",msg);
} while(strcmp(msg,"")!=0);
}

Answer

Because of scanf() wait char-string, separated by whitespaces, enters, etc. So, it just ignores ENTERs, and waiting for "real non-empty string". If you want to get empty string too, you need to use

fgets(msg, 100, stdin);
Comments