【发布时间】:2018-12-11 05:37:42
【问题描述】:
谁能解释为什么我在使用下面的 C++ 代码时遇到问题?
#include <iostream>
using namespace std;
class stud
{
public:
string name,adrs;
long long unsigned int mob;
};
int main()
{
stud s[10];
unsigned int num;
cout << endl << "Enter the number of students(<10): ";
cin >> num;
cout << endl;
for(int i = 0; i < num; i++)
{
cout << endl << "Enter student " << i+1 << " name(put '.' at end and press enter): ";
getline(cin, s[i].name); // this line skips some data before even they are
//entered and there is no error while compiling
}
system("CLS");
for(int i = 0; i < num; i++)
{
cout << endl << " Student " << i+1 << " name is: ";
cout << s[i].name << endl;
}
return 0;
}
当我尝试为上述数组中的对象输入字符串值时,使用不带任何分隔符的getline()(默认使用新行),我没有得到正确的输出,因为其他一些数据是自动的被跳过。
但是,当我使用getline() 而不是上面的方法时,它可以正常工作,但最后需要一个分隔符:
getline(cin, s[i].name, '.');
请帮我找到解决办法。我认为 Enter 键一次按下几次,这就是getline() 跳过一些数据的原因。不过,我不确定。
【问题讨论】:
-
将问题发布为段落,而不是代码中的 cmets。正确缩进和格式化代码。
-
"我认为
Enter键在一次按下时被按下了多次" - 是什么让你这么认为?Enter键通常不是这样工作的。 StackOverflow 不是调试服务。到目前为止,您为自己解决此问题做了哪些工作?您甚至尝试过使用调试器吗?为什么要求用户在名称末尾输入'.'?getline()默认情况下不需要这样做,那么简单地让用户输入Enter来结束名称有什么问题?