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);
}
The "%s" in scanf("%s",... skips over leading whitespace (including "Enter" or \n) and so patiently waits for some non-whitespace text.
Best to take in a \n, use fgets().
char msg[100];
if (fgets(msg, sizeof msg, stdin)) {
// success
If you need to use scanf()
int result = scanf("%99[^\n]%*c", msg);
if (result != 1) handle_rump_line_or_end_of_file_or_IOError();
This will scan in 1 to 99 non-\n chars and then append a \0. It will then continue to scan 1 more char (presumably the \n) but not save it due to the *. If the first character is a '\n', msg is not changed and the '\n' remains in stdin.
Edit (2016): To cope with lines that begin with '\n', separate the scan that looks for the trailing '\n'.
msg[0] = '\0';
int result = scanf("%99[^\n]", msg);
scanf("%*1[\n]");
if (result == EOF) handle_end_of_file_or_IOError();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With