如何解决如何从用户那里获取信息,而不是使用特定值?
已编辑。您好,我在这里还是C ++的新手。我想编写一个可以基本使用函数和类的代码。我从主函数中的用户ID,名称,薪水询问。顺便说一句,在编译之前没有发生错误,程序询问用户ID,但是跳过了我用string定义的名称。然后继续使用薪水。为什么不采用字符串值?在代码末尾我添加输出
enter code here
#include<string>
#include<iostream>
using namespace std;
class Employee
{
private:
int eid;
string name;
public:
Employee(int e,string n)
{
eid=e;
name=n;
setEmployeeID(e);
setName(n);
}
void setEmployeeID(int e)
{
eid=e;
}
int getEmployeeID()
{
return eid;
}
void setName(string n)
{
name=n;
}
string getName()
{
return name;
}
};
class FulltimeEmployee:public Employee
{
private:
int salary;
public:
FulltimeEmployee(int e,string n,int sal):Employee(e,n)
{
salary=sal;
setSalary(sal);
}
void setSalary(int sal)
{
salary=sal;
}
int getSalary()
{
return salary;
}
};
class ParttimeEmployee:public Employee
{
private:
int wage;
public:
ParttimeEmployee(int e,int w):Employee(e,n)
{
wage=w;
setWage(w);
}
void setWage(int w)
{
wage=w;
}
int getWage()
{
return wage;
}
};
int main()
{
int workerId;
string workerName;
int workerPayment;
cout<<"Please enter your ID please: ";
cin>>workerId;
cout<<"Please enter your name please: ";
cout<<"Please enter your salary: ";
getline(cin,workerName);
cin>>workerPayment;
ParttimeEmployee personel1(workerId,workerName,workerPayment);
FulltimeEmployee personel2(workerId,workerPayment);;
cout<<"Daily wage of "<<personel1.getName()<<" is "<<" " <<personel1.getWage()<<endl;
cout<<"Worker ID is:"<<personel1.getEmployeeID()<<endl;
cout<<"Salary of "<<personel2.getName()<<"is "<<" "<<personel2.getSalary()<<endl;
cout<<"Worker ID is:"<<personel2.getEmployeeID()<<endl;
return 0;
}
enter code here
Here is my output:
Please enter your ID please: 12123
Please enter your name please: Please enter your salary: 1000
Daily wage of is 1000
Worker ID is:12123
Salary of is 1000
解决方法
我正在大胆猜测,但是您可以使用cin
:
class Employee
{
//...
public:
void get_info_from_user()
{
std::cout << "Enter employee ID: ";
std::cin >> eid;
std::cout << "Enter employee name: ";
std::getline(std::cin,name);
};
};
您还可以添加与其他类相似的内容。
编辑1:重载运算符>>
要获得更多通用性,您可以重载operator>>
:
class Employee
{
//...
public:
friend std::istream& operator>>(std::istream& input,Employee& e);
};
std::istream& operator>>(std::istream& input,Employee& e)
{
input >> e.eid;
std::getline(input,e.name);
return input;
}
上面的代码允许您执行以下操作:
std::vector<Employee> database;
Employee e;
while (data_file >> e)
{
database.push_back(e);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。