C - trying to read a single char from stdin (and failing) w/ scanf / getchar

后端 未结 4 763
无人共我
无人共我 2020-11-30 12:53

as a part of a homework assignment, I\'m trying to read a single char from stdin, and act according to it:

char choice;

while (1) {
    printf(\"please ente         


        
4条回答
  •  悲&欢浪女
    2020-11-30 13:41

    First of all I will keep it brief.Because of insufficient points to submit a comment If we can see that number of o/p is (one + the no of charcter) This is beacuse when we hit enter after entering the characters '\n' which is non-printable character also gets added after your string.

    $ ./run
    please enter [y]es, [n]o or [m]aybe: y
    you selected yes!
    Please enter only 'y', 'n' or 'm'!  -----------> it is due to reading of the '\n' by scanf
    

    EDITED Due to insufficient points I could post this as a comment.This is a workaround of the above answers

提交回复
热议问题