chess - Confused by the behavior of this simple function -
this function extremely simple, or @ least should be. background: i'm building chess program, , function runs assign promote values pawns have reached end of table. function read promotion requests; detection , actual promotion 1 fxn higher. here's code:
char promote (int player) { char req, out; req = '0'; //shouldn't necessary, , should overwritten scanf out = '0'; //just in case, should overwritten printf("what piece promote to? (q/n/r/b) \n"); scanf("%c", &req); if (req == 'q' || req == 'q') { out = 'q'; } else if (req == 'r' || req == 'r') { out = 'r'; } else if (req == 'n' || req == 'n') { out = 'n'; } else if (req == 'b' || req == 'b') { out = 'i'; } else if (req != 'q' && req != 'q' && req != 'r' && req != 'r' && req != 'n' && req != 'n' && req != 'b' && req != 'b') { printf("req: %c, out: %c \n", req, out); //to test variable values printf("that character invalid. please enter another.\n"); return promote(player); } //a simple else should suffice here. put in else if possible fix via redundancy (didn't work) if(player == 2) { out = toupper(out); //designates team case } printf("returning %c\n", out); //test out value again return out; }
what should happen: fxn scans single-character input, assigns req, checks req against 8 possible choices. if fits in 1 of 4 bins, assigns 1 of 4 values out; if not, prints simple error message , returns own call, @ point scans, etc.
what happen: when called, scanf reads \n (automatically), , spits error message , loops upon without waiting input. in second loop, works fine, 1 caveat: when enter invalid character, returns proper error message, , upon calling again, goes through 1 loop of reading \n before working again. suggests function itself, , not error message, blame.
the output:
you can promote pawn. piece promote to? (q/n/r/b) req: , out: 0 character invalid. please enter another. piece promote to? (q/n/r/b) q returning q
any ideas? i've tried dozen different things trying fix this, , none of 'em have worked. simple big mistakes are. help!
looks scanf
reading newline, previous input. fix this, can loop scanf
until isn't whitespace:
do { scanf("%c", &req); } while(isspace(req));
as aside, can use tolower
convert character lowercase, should simplify req
testing.
Comments
Post a Comment