任何人都可以解释为什么我在使用下面的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()
跳过一些数据的原因。不过,我不确定。
答案 0 :(得分:0)
在对您进行编程之前,要知道的一件事是
实际上,当您从终端提交时选择Enter或Return时,换行符总是附加到输入中。
当用户按下Enter键时,cin >>不会从缓冲区中删除新行。
这与您自己提供的输入无关,而是与默认行为std :: getline()所显示的行为有关。当您提供名称(std :: cin >> num;)的输入时,您不仅提交了以下字符,而且还向流添加了一个隐式换行符,getline()将此与输入一起误认为是用户输入。
如果以后要使用getline(cin,any string),建议使用cin >>(无论如何)之后使用cin.ignore()除去那些多余的字符。 编辑代码的这一部分:
stud s[10];
unsigned int num;
cout << endl << "Enter the number of students(<10): ";
cin >> num;
cout << endl;
cin.ignore();//just add this line in your program after getting num value through cin
//fflush(stdin);
//cin.sync();
//getchar();
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);
}
system("CLS");
您可以使用fflush(stdin)并可能会尝试使用它,但不建议这样做,因为它具有未定义的行为,例如 根据标准,fflush只能与输出缓冲区一起使用,显然stdin不是一个。 关于cin.sync():
在“ cin”语句之后使用“ cin.sync()”会丢弃缓冲区中剩余的所有内容。尽管“ cin.sync()”并非在所有实现中都有效(根据C ++ 11及更高版本的标准)。
您还可以使用getchar()获取由Enter引起的换行符