tags:

views:

76

answers:

2

Hello there,

How can I prevent a given app from creating a newline ('\n') after I request user input in C? I'd like something like:

Type a number
Number: 3x10 = 30

The "x10 = 30" is added after the user inputs the number.. The problem is I can't do it on the same line (and I'd like to do it).

Can anyone help me?

+3  A: 

This is not possible in plain C, and often even not possible in general. The reason is buffering, input streams wait for a character (usually enter) to send data to processors (like scanf, gets, getchar, ...). First of all, stdin itself is buffered. You can turn this off by using setvbuf: setvbuf ( stdin, NULL, _IONBF, 0), which I however do not recommend. This also means you have to handle backspaces and other control characters yourself, ugly stuff (use telnet for some time if you want to know how painful this is).

Secondly, the terminal you work in will often also use buffers, even if you put off buffering in C, this one will buffer until enter is hit. You can try to find system-specific ways to disable buffering here also, but as far as I know these do not exist for every system/terminal.

If you want to control output on this level, system specific API's or even creating custom consoles will be necessary.

KillianDS
+1  A: 

As KillianDS said, most terminals buffer input automatically so you have to tell the terminal interface that you want raw/unbuffered input. Unfortunately, the way to do this will vary between most systems.

On UN*X systems, check out the stty command (e.g. stty raw to set unbuffered and stty sane to go back to normal, these can be called via system or the execl family). You could also use the tcsetattr command from the termios interface.

maerics
I'll probably test the tcsetattr function, then.Thanks! :)
pwseo