为什么第二个字符丢失了第二个变量

Why the second character is getting lost for the second variable

我有 2 个 char 类型的变量。

char desc[30];
char code[2];
cout << "Enter values : "<<"\n";
cin.getline(desc,30);
cin.getline(code,2);

cout << "\nValues Entered: "<<"\n";
cout << desc <<"\t";
cout << code <<"\n";

当输入值如下所示时,第二个变量的第二个字符丢失。我试过 cin>>markscin.get(marks,2),但行为始终相同。

Enter values :
This is a test line
LH

Values Entered:
This is a test line     L

Process returned 0 (0x0)   execution time : 11.285 s
Press any key to continue.

在上面的示例中,即使输入是 LH,在输出中也只有 'L' 可用并且 'H' 丢失。有人可以告诉我这里出了什么问题吗?

看看 getline 的文档(强调我的):

Maximum number of characters to write to s (including the terminating null character).

所以如果你想读入两个符号,你必须放3的大小。

cin.getline(code,3);

也将您的缓冲区大小更改为 3

char code[3];