重叠的cout

时间:2013-12-05 00:24:38

标签: c++ loops eof

由于某种原因,第二次迭代此循环时,cout语句重叠。换句话说,在第一个cout之后,程序不等待输入。我该如何解决这个问题?

另外,在现实生活税的情况下,nPay功能是否正常?有人告诉我,税收应该乘以毛额,每个人都要加上。但是,我的方法也会起作用,特别是因为它们同时发生。

double calcGrossPay (double payRate, double hours);
double nPay (double& fedTx, double& localTx, double& stateTx, double& ssTx, double& netPay, double fPay);
void displayAll (double fPay, double netPay, string name);

double fedTx = 14, stateTx = 6, localTx = 3.5, ssTx = 4.75;

int main()
{

    while (!cin.eof())
    {
          string name;

          //cin.ignore();
          cout <<"Please enter your working name: ";
          getline (cin, name);
          !cin.eof();

          double payRate, hours;

          cout <<"Enter your pay rate and hours worked, respectively."<< endl;
          cin >> payRate >> hours;
          !cin.eof();

          double fPay = calcGrossPay (payRate, hours);

          double netPay = 0;
          netPay = nPay (fedTx, localTx, stateTx, ssTx, netPay, fPay);
          displayAll (fPay, netPay, name);

           system("pause");
    }
}


double calcGrossPay (double payRate, double hours)
{
       double extraT, fPay;
       if (hours > 40)
       {
       extraT = (hours - 40) * (1.5 * payRate);
       fPay = extraT + (40 * payRate);
       }
       else
       fPay = payRate * hours;

       return fPay;
}

double nPay (double& fedTx, double& localTx, double& stateTx, double& ssTx, double& netPay, double fPay)
{
       double totalTx = fedTx + localTx + stateTx + ssTx;
       netPay = fPay * (1 - (totalTx / 100));
       return netPay;
}

void displayAll (double fPay, double netPay, string name)
{
    cout <<"Below is "<< name << "'s salary information" << endl;

     cout << fixed << showpoint << setprecision(2) <<"\nYour calculated gross pay is $"
          << fPay << ", and your net pay is $" << netPay << endl;
}

1 个答案:

答案 0 :(得分:2)

getline之后,流中仍有新行,因此您必须ignore

getline(cin, name);
cin.ignore();

此外,在检查流之前,请执行提取而不是while (!cin.eof())

while (getline(cin, name))
{
    cin.ignore();
    // ...
}

这是更新的代码。我希望它适合你:

int main()
{
    for (std::string name; (cout << "Please enter your working name: ") &&
                            getline(cin >> std::ws, name);)
    {
        if (cin.eof())
            break;

        double payRate, hours;

        cout << "\nEnter your pay rate and hours worked, respectively." << endl;

        if (!(cin >> payRate >> hours))
            break;

        double fPay = calcGrossPay(payRate, hours);

        double netPay = nPay(fedTx, localTx, stateTx, ssTx, netPay, fPay);

        displayAll(fPay, netPay, name);
        cin.get();
    }
}