开发者

Control keys (left arrow) are sent to stdin (^[[D) instead of being interpreted

When reading user input using getline(cin, mystrvar), some control keys don't work.

Example:

User input: abc^[[Dd
Text: abd
User input: asc
Read bytes: 7
#0: 97
#1: 98
#2: 99
#3: 27
#4: 91
#5: 68
#6: 100

I typed a, b, c, then left arrow and d. "Text:" apparently writes (cout) the first three characters, then sets the pointer to the left and overwrites the c. "asc" is a simple function that prints the length (mystrvar.siz开发者_开发问答e()) and ascii values.

When calling "stty -ctlecho" (system(...)), I am able to use the left arrow key, but it isn't limited to my input (I can overwrite "User input: ") plus the control codes are still being sent to my program.

This does not happen on Windows - I can use the arrow keys (even up/down for history) normally.

What's wrong here?

Edit: I'm mostly using Fedora 15. There doesn't seem to be any difference between lxterminal, terminal, xterm, konsole, gnome-terminal (as terminal) or bash, ksh, tcsh (as shell).


How those keys work is a property of your terminal, not of the c++ program. The program gets the input line buffered, and your terminal is responsible for assembling that line.


Although it shouldn't have anything to do with the program (that receives the stdin), I've found a workaround, which requires a slightly different behavior of the program:

#include <readline/readline.h>
#include <readline/history.h>

string blah()
{
    string str;

    cout << "User input (readline): ";

    char *inp_c = readline(""); //Instead of getline()

    str = (const char *)(inp_c); //Because C strings stink

    //...

    return str;
}

This works. I couldn't compile it on Windows though. error: readline/readline.h: No such file or directory Apparently this isn't a standard header, so I have to get/install it first.

If anyone knows a better way, please let me know !


PlasmaHH is right, how those keys are handled depends on the terminal. But not only : The shell interpreter also plays its part.

So an easy suggestion : use "bash", which handle those keys correctly by default (on my machine at last ;-)

Just launch "bash" and retry.


OK, another try then.

who do you think is providing you the inline editing feature ? (ability to go back, delete, etc. before pressing enter)

Not your program, of course. So it has to be another program. Which one ? Since it's not the shell, would say the console you are using. It looks like windows cmd prompt provide this feature. Linux console should provide it as well, but it may have been deactivated or a packet is needed.

You say you are not using a remote connection. But what console are you using ? Try "konsole" (kde console) or other variants your system may have.

If there is no program to interpret those special keys, they are just appended into the input buffer...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜