Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

terminal

I would like to ask if there's any way to keep the cursor in the current line after pressing ENTER !!

for example ...

#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;
}

An example of output :

Enter a number : 10
 is a Even number

... but what I need is something like that :

Enter a number : 10 is a Even number 

I want to put "is a Even number" (or " is a Odd number") next to the number entered by user

like image 477
Az.Youness Avatar asked May 29 '13 12:05

Az.Youness


3 Answers

The user is pressing enter, and this is being echoed back and starting a new line.

In order to avoid this, you'll need to turn off echo (and then read and echo individual characters except for newline). This is system-dependent, for example on Linux you can put the tty into raw/uncooked mode.

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

like image 168
Ben Voigt Avatar answered Oct 30 '22 10:10

Ben Voigt


The simple answer is "you can't". There is no standard C++ functions to control this behaviour, or to read data without hitting enter at the end (in fact, the data hasn't really been "entered" until you hit enter, so the program won't see the data).

You can use non-standard functionality, such as additional libraries, such as a "curses" library or system dependent code, but we would then have to produce the code to read characters one at a time and merge it together using code that you write.

I would suggest that you use the "repeat the input in the output", and simply do something like this:

printf("%d is", d);
if (d%2)
    printf("an odd number\n");
else
    printf("an even number\n");
like image 1
Mats Petersson Avatar answered Oct 30 '22 10:10

Mats Petersson


Set up raw keyboard mode and disable canonical mode. That's almost, how linux manages not to show password chars in terminal.

Termio struct is the thing you should google for.

One link is :

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

The Constants of the assembly are also available for a syscall ioctl.

like image 1
icbytes Avatar answered Oct 30 '22 11:10

icbytes