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

百般思念 提交于 2019-12-12 10:48:23

问题


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


回答1:


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



回答2:


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.




回答3:


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.




回答4:


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



回答5:


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



来源:https://stackoverflow.com/questions/16814167/c-c-can-i-keep-the-cursor-in-the-current-line-after-pressing-enter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!