c++ - 我觉得我放入结构中的输入代码可以压缩,关于如何在保持代码简短的同时保持数据独立的任何建议?
问题描述
我一直在试图弄清楚如何将信息输入到我的结构中,但我想压缩代码。
#include <iostream>
using namespace std;
struct Employee //The whole program is going to revolve around this struct
{
char first[10], last[10];
float Hours_Worked, Hourly_Rate, Fed_Tax_Rate, St_Tax_Rate;
}Kobe, Lebron, Larry, Michael; //Struct declarations
这里的代码就是我正在谈论的代码。我的首选设计是使用循环 4 次的 for 循环,但是我需要单独的信息。
int main()
{
Employee Kobe;
cout << "First name: ";
cin >> Kobe.first;
cout << "Last name: ";
cin >> Kobe.last;
cout << "Hours worked: ";
cin >> Kobe.Hours_Worked;
cout << "Federal Tax Rate: ";
cin >> Kobe.Fed_Tax_Rate;
cout << "State Tax Rate: ";
cin >> Kobe.St_Tax_Rate;
Employee Lebron;
cout << "First name: ";
cin >> Lebron.first;
cout << "Last name: ";
cin >> Lebron.last;
cout << "Hours worked: ";
cin >> Lebron.Hours_Worked;
cout << "Federal Tax Rate: ";
cin >> Lebron.Fed_Tax_Rate;
cout << "State Tax Rate: ";
cin >> Lebron.St_Tax_Rate;
Employee Larry;
cout << "First name: ";
cin >> Larry.first;
cout << "Last name: ";
cin >> Larry.last;
cout << "Hours worked: ";
cin >> Larry.Hours_Worked;
cout << "Federal Tax Rate: ";
cin >> Larry.Fed_Tax_Rate;
cout << "State Tax Rate: ";
cin >> Larry.St_Tax_Rate;
Employee Michael;
cout << "First name: ";
cin >> Michael.first;
cout << "Last name: ";
cin >> Michael.last;
cout << "Hours worked: ";
cin >> Michael.Hours_Worked;
cout << "Federal Tax Rate: ";
cin >> Michael.Fed_Tax_Rate;
cout << "State Tax Rate: ";
cin >> Michael.St_Tax_Rate;
return 0;
}
解决方案
Employee
用输入法定义a来获取输入
struct Employee
{
char first[10], last[10];
float Hours_Worked, Hourly_Rate, Fed_Tax_Rate, St_Tax_Rate;
bool getinput(std::istream & in,
std::ostream & out);
};
然后你实现这个方法
bool Employee::getinput(std::istream & in,
std::ostream & out);
{
out << "First name: ";
in >> first;
out << "Last name: ";
in >> last;
out << "Hours worked: ";
in >> Hours_Worked;
out << "Federal Tax Rate: ";
in >> Fed_Tax_Rate;
out << "State Tax Rate: ";
in >> St_Tax_Rate;
return in.good(); //always good to know if the input succeeded
}
然后你调用方法
Employee Kobe;
Kobe.getinput(cin, cout);
Employee Lebron;
Lebron.getinput(cin, cout);
Employee Larry;
Larry.getinput(cin, cout);
Employee Michael;
Michael.getinput(cin, cout);
cin
并cout
以抽象形式传入,以便您可以调用getinput
不同的输入流,例如网络套接字。
推荐阅读
- python - 如何在 Ubuntu 20.04 上为 Python 3.9 安装 pip
- python - “锯状”函数的根
- vue.js - Vue 的组合 API ref 包含数据,当 .value 被调用时返回 null
- php - 具有 xss 漏洞的搜索字段
- swift - Environmentobject 跟踪数组变量
- pandas - 如果值包含单词的复数形式,如何删除一行?
- c# - c# 列表中值的总和
- html - 浏览器自动添加“空白”并在我放入时显示“_” (单独一行)
- amazon-web-services - 在完成所有基本步骤后,我无法通过 ipv6 从 aws ec2 连接(我从互联网上学到的)
- visual-studio-code - Deno 应用程序的 Vscode 调试错误:无法连接到调试目标