I want to write a C program that tokenizes a string and prints it out word by word, slowly, and I want it to simultaneously listen for the user pressing Enter, at which point they will be able to input data. Is this possible?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Update: see @modifiable-lvalue ‘s comment below for additional helpful information, e.g., using
getchar()instead of getch(), if you go that route.Definitely possible. Just be aware that
gets()may not be entirely helpful for this purpose, sincegets()interprets enter not as enter per se, but as “now, I the user, have entered as much string as I want to”. So the input gathered bygets()from pressing just an enter will appear as an empty string (which might be workable for you).See: http://www.cplusplus.com/reference/cstdio/gets/.
But there are other reasons not to use gets()–it does not let you specify a maximum to read in, so it’s easy to overflow whatever buffer you are using. A security and bug nightmare waiting to happen. So you want
fgets(), which allows you to specify a maximum size to read in.fgets()will place a newline in the string when an enter is pressed. (BTW, props to @jazzbassrob on fgets()).You could also consider something like
getch()–which really deals with individual key-presses (but it gets a bit complicated handling keys that have non-straightforward scan-codes). You may find this example helpful: http://www.daniweb.com/software-development/cpp/code/216732/reading-scan-codes-from-the-keyboard. But because of the scancodes issues,getch()is subject to platform details.So if you want a more portable approach, you may need to use something heavier weight, but fairly portable, such as ncurses.
I suspect you can do what you want with either
fgets(), keeping in mind that enter will give you a string with just a newline in it, orgetch().I just wanted you to be aware of some of the implementation/platform issues that can arise.
C can absolutely do this, but it’s a little more complicated than one might guess at first attempt. That’s because terminal input is, historically, very platform dependent.