我有 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>>marks
和 cin.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];
关于c++ - 为什么第二个字符丢失了第二个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57992491/