0
#include<conio.h>
#include<iostream>
using namespace std;
class Student
{
private:
char name[20];
char rollno[20];
public:
void input();
void display();
};
class Acadamic_details:public Student
{
private:
float marks,percentage;
public:
void input();
void display();
};
class Guardian_details:public Acadamic_details
{
private:
char F_name[20],M_name[20];
public:
void input();
void display();
};
void Student::input()
{
cout<<endl<<" Enter the Name : ";
cin.getline(name,30,'\n');
cout<<endl<<" Enter the Roll No :";
cin.getline(rollno,30,'\n');
}
void Acadamic_details::input()
{
Student::input();
cout<<endl<<" Enter the Marks out of 500 :";
cin>>marks;
}
void Guardian_details::input()
{
Acadamic_details::input();
cout<<endl<<" Enter the Father's Name :";
cin.getline(F_name,30,'\n');
cout<<endl<<" Enter the Mother's Name :";
cin.getline(M_name,30,'\n');
}
void Student::display()
{
cout<<endl<<" Name : "<<name<<endl;
cout<<" Roll No : "<<rollno<<endl;
}
void Acadamic_details::display()
{
Student::display();
percentage=(marks/500)*100;
cout<<endl<<" Marks : "<<marks<<"/500"<<endl;
cout<<" Percentage : "<<percentage<<"%"<<endl;
}
void Guardian_details::display()
{
Acadamic_details::display();
cout<<endl<<" Father's Name : "<<F_name<<endl;
cout<<" Mother's Name : "<<M_name<<endl;
}
int main()
{
Guardian_details g1;
cout<<" Enter the Student's Details "<<endl;
g1.input();
cout<<" Student's Details Are : "<<endl;
g1.display();
getch();
return 0;
}
这是多级继承的实现。 编译期间没有编译错误。 但是当我执行的程序,我面临着一个运行时间问题如何解决C++代码片段cin.getline的运行时跳过问题
void Guardian_details::input()
{
Acadamic_details::input();
cout<<endl<<" Enter the Father's Name :";
cin.getline(F_name,30,'\n');
cout<<endl<<" Enter the Mother's Name :";
cin.getline(M_name,30,'\n');
}
从上面的代码段,cin.getline(F_name,30,'\n');
不工作。 每次运行程序它直接执行cout<<endl<<" Enter the Mother's Name :"; cin.getline(M_name,30,'\n');
跳过cin.getline(F_name,30,'\n');
。
谁能解释为什么发生得如此,什么是替代该代码。
在此先感谢。
我该如何解决这个问题? –
@KunalVerma无处不在使用'getline',只使用'>>'运算符?或者使用'getline'获取数字,并将字符串转换为数字?或[忽略](http://en.cppreference.com/w/cpp/io/basic_istream/ignore)下一个字符,直到换行符为止? –
找到解决方案。 (使用(cin >> marks).ignore();) –