-1

I'm trying an example from "The C programming language" on Windows with CodeBlock and I don't know how I can get user input without having to press enter. This program counts the number of lines in the input using getchar() and so when I run it "enter" only works as a \n and doesn't allow me to send my input. Is there an alternative way to do it?

EDIT the problem was with the compiler. Figured it out after looking into it for some time

MatSiv97
  • 11
  • 2
  • 1
    Look into the `getch` function, which gets one key press. You could of course use a loop to execute `getch` as many times as needed. I have a feeling that there's probably a higher-level way of doing this though. – Aaron Christiansen Aug 12 '16 at 20:19
  • 1
    `This program counts the number of lines in the input` Which Program? – Michi Aug 12 '16 at 20:35

1 Answers1

0

This is not a problem of the C programming language. It has more to do with the terminal that you are using to interface with the C program.

By default, most terminals buffer the input that you type and only send it to the program when you finish the line by pressing enter. This is what allows you to use the backspace key to correct typing mistakes before they are sent to the C program.

If you are not creating an interactive program, then if you redirect the program output to read from a file instead of from the terminal then getchar() will not have to wait. After all, the input file is all there from the start.

./myprogram.exe < myinputfile.txt

If you want to create an interactive program then the simplest thing you can do is to accept that the input comes one full line at a time. It is what users typing at the terminal will expect.

If you want your application to immediately respond to keypresses then you will need to use something outside the standard C library. For example, in Linux you could use ncurses to create terminal applications that can immediately react to a keypress, including arrow keys and so on.

hugomg
  • 68,213
  • 24
  • 160
  • 246