Problems with character input using scanf()

后端 未结 4 679
暖寄归人
暖寄归人 2020-11-27 22:24

I\'m trying to input a character into a linked list, where the character can be \'A\',\'a\',\'G\',\'g\',\'T\',\'t\',\'C\' or \'c\'.

I\'m not yet familiar with C and

相关标签:
4条回答
  • 2020-11-27 22:33

    Use

    newChar=getche();
    

    This is a nonstandard function that gets a character from the keyboard, echoes to screen.

    0 讨论(0)
  • 2020-11-27 22:35

    You don't handle the newline. The %c specifier doesn't skip blanks. Try:

    scanf(" %c", &newChar);
        /* ^ <-- Makes `scanf` eat the newline. */
    

    Or maybe add an explicit test.

    scanf(...);
    if (newChar == '\n')
        continue;
    
    0 讨论(0)
  • 2020-11-27 22:52

    add space to "%c" to catch the newline character. the space charcter is used to catch space characters, tabulations, newline

    scanf("%c ",&newChar);
    
    0 讨论(0)
  • 2020-11-27 22:55

    You're leaving the '\n' on stdin:

    scanf("%d",&navigate);  
    getchar(); // consume the newline character
    ...
    scanf("%c",&newChar);
    getchar(); // consume the newline character
    

    Or since you're already using scanf() you can tell scanf itself to take care of the newline character:

    scanf("%d\n", &navigate);
    ....
    scanf("%c\n",&newChar);
    

    Even better you can leave it open by adding a space after the format specificer:

    scanf("%d ", &navigate);
    ....
    scanf("%c ",&newChar);
    

    Just in case the user wants to do something like: 2<tab key><enter key>

    Regardless of how you handle it, the point is you need to consume the newline character.

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