Overlapping cout

Overlapping cout

本文关键字:cout Overlapping      更新时间:2023-10-16

由于某种原因,第二次迭代此循环时,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;
}

getline之后,一个新行仍在流中,因此您必须ignore it:

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