Az.Youness
Az.Youness

Reputation: 2652

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

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

Upvotes: 6

Views: 4887

Answers (5)

xtof pernod
xtof pernod

Reputation: 883

This trick may help, if you have a vt100-style terminal: cursor movements.

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

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

Upvotes: 1

icbytes
icbytes

Reputation: 1851

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.

Upvotes: 1

Mats Petersson
Mats Petersson

Reputation: 129374

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");

Upvotes: 1

Exceptyon
Exceptyon

Reputation: 1582

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

OR, try to play with printf("%c", (char)8); if I remember correctly that's a backspace

otherwise, you'll probably have to use some output lib such as ncurses

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283684

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.

Upvotes: 3

Related Questions