0

I try to get user input using getline fucntion. User may type chinese charactors, some backspaces and some other charactors. Then I meet an issue. What I get in program is not I typed in termial.

My code likes below:

int main(int argc, chart argv[]) {

cout << ">>";
char *cmdBuf = (char*)malloc(1024);
while(true)
{    
    size_t cmdLen = 1024;   
    ssize_t readNum = getline(&cmdBuf, &cmdLen, stdin);
    if (readNum == -1 || readNum == 1)   
    {    
         cout << ">>";
         continue;
    }
    cout << "readNum: " << readNum << ". The input is: << cmdBuf;
    cout << ">>;  
}

free(cmdBuf) ; 
return 0;

}

Execute the program in shell and get the results below('在' is a chinese charactor):

user input: display program output: readNum: 8. The input is: display

user input: display在 program output: readNum: 11.The input is:display在

user input: display在[backspace][backspace] ----------------- The termial shows "display". program output: readNum: 9. The input is: display[a garbled character]

user input: display在[backspace][backspace][backspace] ----------------- The termial shows "displa". program output: readNum: 8. The input is: display enter image description here

From the results, '在' contains 3 charactors. However, if I type '在', I only need type 2 backspaces to clear '在' and then I will get a wrong input in C++ program.

What should I do to make sure what C++ program get from stdin is what user see in the terminal?

KeKe
  • 177
  • 1
  • 1
  • 5

0 Answers0