c program doesn't work scanf char

后端 未结 2 1465
北荒
北荒 2020-12-22 09:59
#include 
int main() {

    struct cerchio c1, c2;
    float distanza;
    char k;

    //input del centro del primo cerchio
    printf(\"Enter the co         


        
相关标签:
2条回答
  • 2020-12-22 10:36
    scanf("%s", &k); 
    

    should be

    scanf(" %c", &k); 
    

    %c is the right format specifier for a character(char) while %s is used for strings. The space character behind %c skips all whitespace characters including none, until the first non-whitespace character as specified in the C11 standard:

    7.21.6.2 The fscanf function

    [...]

    1. A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails

    The reason why your program wouldn't wait for further input when you used %c is because there was a newline character(\n) prevailing in the standard input stream(stdin). Remembering pressing enter after entering data for each scanf? The newline character is not captured by the scanf with %f. This character is instead captured by the scanf with %c. This is why this scanf doesn't wait for further input.

    As for why your other scanfs(with a %f) did not consume \n is because the %f skips whitespace characters as seen in the C11 standard:

    7.21.6.2 The fscanf function

    [...]

    1. Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier. 284

    As for why your program worked when you used is because you were lucky. Using %s instead of %c invokes Undefined Behavior. This is because %s matches a sequence of non-whitespace characters and adds a NUL-terminator at the end. Once a user enters anything, the first character is stored in k while the rest of the characters(if any) as well as the \0 is written in an invalid memory location.

    If you are currently thinking why the %s format specifier did not consume the \n is because it skips whitespace characters.

    0 讨论(0)
  • 2020-12-22 10:40

    use

    scanf(" %c",&k);
    

    Instead of

    scanf("%s", &k); // %s is used for strings, Use %c for character variable.
    

    for char variable use " %c". and don't forget to keep space before %c " %c" , it will skips newline and whitespace characters.

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