简体   繁体   中英

pause function in C does not respond to enter key

char keyin, buffer[1024]; 
do 
{ 
 keyin=gets(buffer);
} 
while (keyin != "\n");

I have been trying to write a pause function in C where a user exits a paused state by pressing the Enter key. Where the user writes "pause" and this function gets executed. I have been working on this function for a while and it eludes me. I have implemented the code in several different ways and none of them work. I suspect it's because the comparison of "\\n" with keyin. I think "\\n" does not directly translate to the enter key.

You do not need a while loop to wait for a single Enter key press. It will wait (and you can press any key) until you press Enter: http://en.cppreference.com/w/c/io/gets

But you need to reserve a lot of space -- what if someone keeps pressing any other key "until something happens"? The buffer will overflow, and your program will (most likely) crash.

You probably want to use getchar -- this will send one keypress at a time back.

Note: the Enter key typically sends the ASCII code 13 (0x0D), not 10 (0x0A). You could use '\\r' instead (minding others' notes on 'character' vs. "string"!), or prevent all confusion and use the hex or dec value.

This is different from the behavior of '\\n' you are used to when outputting, because only certain functions will expand or convert the code '\\n' in text to the required end-of-line sequence for your OS.

You cannot compare strings with == or != in C. You must compare the contents of the strings with a function like strcmp (or, preferably, one of the safer variants), eg:

while (strcmp(keyin, "\n") != 0);

As an aside, you should never ever actually use gets . It is impossible to use safely and securely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM