You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++工资计算程序输入含空格姓名时跳过工时输入问题求助

C++工资计算程序问题修复

问题原因

  • cin >> name 以空白字符(空格、换行、制表符)作为输入终止符,输入含空格的姓名(如"Mr Adam")时,name仅获取到空格前的部分("Mr"),剩余内容("Adam")会被后续的cin >> hours读取。由于"Adam"不是有效浮点数,hours会被赋值为0(或未定义垃圾值),程序直接跳过工时输入步骤进入计算逻辑。
  • 原代码中wage变量未初始化就使用+=操作,会导致工资计算结果为不可预期的垃圾值。

修复方案

  1. 使用getline(cin, name)替代cin >> name,实现读取包含空格的完整姓名。
  2. 初始化wage变量,避免未定义行为。

修复后的完整代码

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

int main() {
    string name;
    float hours, wage = 0.0f, netwage, SocsoContribution, HoursBalance;
    
    cout << "WELCOME TO XYZ\n";
    cout << "Please enter your name: ";
    getline(cin, name);
    
    cout << "Please enter your hours worked: ";
    cin >> hours;
    cout << "\n\n";

    if (hours > 60) {
        HoursBalance = hours - 60;
        wage += (40 * 5) + (20 * 8) + HoursBalance * 10;
    } else if (hours > 40) {
        HoursBalance = hours - 40;
        wage += 40 * 5 + HoursBalance * 8;
    } else {
        wage = hours * 5;
    }

    SocsoContribution = 0.01 * wage;
    netwage = wage - SocsoContribution;

    cout << "PAYSLIP\n";
    cout << "Name: " << name << "\n";
    cout << "Hours worked: " << hours << " Hour(s)\n";
    cout << "Wage: RM" << wage << "\n";
    cout << "Socso Contribution: RM" << SocsoContribution << "\n";
    cout << "Net Wage: RM" << netwage << "\n";

    return 0;
}

额外说明

  • 修复后的代码简化了HoursBalance的赋值逻辑,去掉了冗余的HoursBalance = hours语句,让代码更简洁。
  • 若后续在getline前有读取数字的cin操作,需要先调用cin.ignore()清空输入缓冲区中的换行符,避免getline读取到空行。

内容的提问来源于stack exchange,提问作者AnsMklss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:35:20