How to read from input until newline is found using scanf()?

后端 未结 8 1637
野性不改
野性不改 2020-11-30 05:58

I was asked to do a work in C when I\'m supposed to read from input until there\'s a space and then until the user presses enter. If I do this:

scanf(\"%2000         


        
8条回答
  •  感动是毒
    2020-11-30 06:32

    scanf (and cousins) have one slightly strange characteristic: any white space in the format string (outside of a scanset) matches an arbitrary amount of white space in the input. As it happens, at least in the default "C" locale, a new-line is classified as white space.

    This means the trailing '\n' is trying to match not only a new-line, but any succeeding white-space as well. It won't be considered matched until you signal the end of the input, or else enter some non-white space character.

    To deal with this, you typically want to do something like this:

    scanf("%2000s %2000[^\n]%c", a, b, c);
    
    if (c=='\n')
        // we read the whole line
    else
        // the rest of the line was more than 2000 characters long. `c` contains a 
        // character from the input, and there's potentially more after that as well.
    

提交回复
热议问题