无法读取和存储用户输入

时间:2011-12-09 03:15:19

标签: c++ class

我在使用C ++编写程序时遇到了严重问题。我需要阅读用户输入的一行信息,例如:

Bill Jones 20   07:30 09:30  08:00 14:00     00:00 00:00    10:00 13:00 00:00 00:00

这应该全部存储在Worker类的一个实例中。我遇到麻烦的是他们使用分号的时间。我完全陷入困境,到处都看,但找不到任何帮助。这是我到目前为止的代码:

#include <iostream>
#include <string>
using namespace std;

class Time;
class Worker;

ostream &operator << (ostream &, const Time &);
istream &operator >> (istream &, Time &);

class Time
{
private:
    int hour;
    int minute;
public:
    Time();

    void setHour(int a)
    { hour=a; }

    void setMinute(int a)
    { minute=a; }

    int getHour() const
    { return hour; }

    int getMinute() const
    { return minute; }

    Time operator + (const Time &);
};

class Worker
{
public:
    int start;
    int end;
    string fName;
    string lName;
    double payrate;
    double payment;

    Time monday,tuesday,wednesday,thursday,friday;
    friend istream &operator >> (istream &, Time &);
    friend ostream &operator << (ostream &, const Time &);
};

Time::Time()
{
    hour = 0;
    minute = 0;
}

ostream &operator << (ostream &strm, const Worker &obj)
{
    strm << obj.fName << " " << obj.lName << " " << obj.payrate;
    return strm;
}

istream &operator >>(istream &strm, Worker &obj)
{
    strm >> obj.fName;
    strm >> obj.lName;
    strm >> obj.payrate;
    string token;
    int h,m;
    string t;
    for (int i=0; i<token.size(); i++) {
        if(token[i]==':')
        {
            h = atoi (t.c_str());
            t.clear();
        }
        else
        {
            t=t+token[i];
        }
        m=atoi(t.c_str());
    }

    obj.monday1.setHour(h);
    obj.monday1.setMinute(m);
    return strm;
}

Time Time::operator+ (const Time &right)
{
    Time temp;
    temp.hour = hour + right.hour;
    temp.minute = minute + right.minute;
    return temp;
}

int main ()
{
    Time time1, time2;
    Worker worker[100];
    int num;
    cout << "Please enter the number of workers on the payrole: ";
    cin >> num;
    cout << "Please input the worker’s last name, first name, pay rate, start time, and end time from "<< endl;
    cout << "Monday through Friday separated by space." << endl;
    for (int i=0; i<num; i++)
    {
        cin >> worker[i];
    }
    for (int i=0; i<num; i++)
    {
        cout << worker[i];
    }

    return 0;
}

1 个答案:

答案 0 :(得分:3)

在以下代码块中,您使用tokent的内容而不事先初始化其值:

string token;
int h,m;
string t;
for (int i=0; i<token.size();i++){
    if(token[i]==':')
    {
        h = atoi (t.c_str());
        t.clear();
    }