首页 > 解决方案 > 我觉得我放入结构中的输入代码可以压缩,关于如何在保持代码简短的同时保持数据独立的任何建议?

问题描述

我一直在试图弄清楚如何将信息输入到我的结构中,但我想压缩代码。

#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;
}

标签: c++struct

解决方案


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);

cincout以抽象形式传入,以便您可以调用getinput不同的输入流,例如网络套接字。


推荐阅读