scanf reading “Enter” key

后端 未结 3 1703
既然无缘
既然无缘 2021-01-03 14:23

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

#include 
#include 
#include 

int main(int a         


        
相关标签:
3条回答
  • 2021-01-03 14:57

    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() as suggested by @maxihatop

    fgets(msg, 100, stdin);
    

    If you need to use scanf()

    int result = scanf("%99[^\n]%*c", msg);
    if (result != 1) handle_IOError_or_EOF();
    

    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_IOError_or_EOF();
    
    0 讨论(0)
  • 2021-01-03 15:13

    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);
    
    0 讨论(0)
  • 2021-01-03 15:15

    Scanf looks through the input buffer for the specified format, which is string in this case. This has the effect of skipping your whitespaces. If you put a space between wording, it skips the space looking for the next string, similarly it will skip tabs, newlines etc. See what happens if you put a %c instead. It will pick up the newline because it is searching for a char now, and '\n' constitutes as a valid char.

    If you want the same effect while getting whitespace, change it to a %c and remove the newline escape character at the print statement.

    0 讨论(0)
提交回复
热议问题