Problems with character input using scanf()

后端 未结 4 708
暖寄归人
暖寄归人 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条回答
  •  萌比男神i
    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

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

提交回复
热议问题