开发者

Ignore carriage returns in scanf before data.... to keep layout of console based graphics with conio.h

I have the misfortune of having use conio.h in vc++ 6 for a college assignment,

My problem is that my graphic setup is in the center of the screen...

e.g.

gotoxy( getcols()/2, getrows()/2);
printf("Enter something");
scanf( "%d", &something );  

now if someone accidentally hits enter before they enter the "something", then the cursor gets reset to the left of the screen on the next line.

Iv tried flushing the keyboard and bios buffers with fflush(stdin) and getchar(), whi开发者_如何学编程ch like I expected didn't work!

Any help/ideas would be appreciated, Thanks, V


Try reading the user's input one character at a time. If a leading carriage return is detected, ignore the character and run your gotoxy( getcols()/2, (getrows()/2)+1) code again to re-place the cursor at the appropriate location (adding one row to avoid writing over the previously-output message).


The road to success will involve doing what the assignment asks you to do :) In particular, you should use one or more functions from conio.h to read your input. scanf() is not a conio.h function.

Because I'm lazy this is a homework question, I won't write the code for you.

One possibility would be to use cscanf() rather than scanf(). But this may (I don't know) echo input characters, which would include that accidental Enter, and not solve your problem.

If this is the case, my strategy would be to write a loop to gather characters entered from the keyboard, using the non-echoing getch() function. You can ignore newlines until you have at least one printable character, and then accept characters (and store them in a character array or whatever) until you get a newline. Since input characters won't be echoed, I think the cursor will not move.

You can then scan the input characters from your input buffer using sscanf(). You'll want to count input characters to make sure your user doesn't overflow your buffer. Also, probably some error handling in case of bad data.

EDIT: Something I forgot to mention: Your last input character in the buffer should be followed by a zero character ( '\0' ) so sscanf() will terminate properly. It's possible for your buffer to be full of zeros by default, but putting one in there intentionally (e.g. when you hit your final newline) will make your code more correct and robust.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜