C / C ++: Can I hold the cursor in the current line after pressing ENTER?

I would like to ask if there is a way to keep the cursor in the current line after pressing ENTER!

eg...

#include<stdio.h> int main() { int d=0; printf("Enter a number : "); scanf("%d",&d); if(d%2)printf(" is a Odd number\n"); else printf(" is a Even number\n"); return 0; } 

Output Example:

 Enter a number : 10 is a Even number 

... but I need something like this:

 Enter a number : 10 is a Even number 

I want to put โ€œthis is an even numberโ€ (or โ€œis an odd numberโ€) next to the number entered by the user

+6
source share
5 answers

The simple answer is "you cannot." There are no standard C ++ functions to control this behavior or to read data without falling into the end (in fact, the data was not actually entered until you hit enter, so the program will not see the data),

You can use non-standard functionality, such as additional libraries, such as a curse library or system code, but we will need to generate code to read characters one at a time and combine it together using the code that you write.

I would suggest that you use "repeat input on output" and just do something like this:

 printf("%d is", d); if (d%2) printf("an odd number\n"); else printf("an even number\n"); 
+1
source

The user presses enter, and this returns in the opposite direction and a new line begins.

To avoid this, you need to disable the echo (and then read and display the individual characters, except for a new line). It depends on the system, for example on Linux you can put tty in raw / raw mode.

You can find a library such as the GNL readline that does most of the work for you.

+3
source

Set raw keyboard mode and disable canonical mode. It is almost like Linux cannot display password passwords in the terminal.

Termio struct is what Google needs.

One link:

http://asm.sourceforge.net/articles/rawkb.html

Assembly constants are also available for syscall ioctl.

+1
source

This trick can help if you have a terminal like vt100: move the cursor.

\033 - ESC, ESC + [ + A - cursor up, ESC + [ + C - right cursor

 int main() { int d=0; printf("Enter a number : "); fflush(stdout); scanf("%d",&d); printf("\033[A\033[18C%d is a an %s number\n", d, d%2 ? "odd" : "even"); return 0; } 
+1
source

not with printf and scanf ... have you tried with getc() and ungetc(char) ?

OR, try playing with printf("%c", (char)8); if I remember correctly that backspace

otherwise you may have to use some output libraries like ncurses

0
source

Source: https://habr.com/ru/post/946086/


All Articles