用户无法输入第二个变量。 C ++

时间:2018-02-10 23:26:32

标签: c++

每当我运行程序时,我只能为第一个变量employeeName输入一个值,但是当我在输入值后按Enter键时,我得到一个"按任意键继续&#34 34;提示。有人可以告诉我出了什么问题吗?

// Calculate how many hours an employee has worked

#include <iostream>
using namespace std;

int main() 
{


    //Declare Named Constants
    int const HOURS_IN_WORK_WEEK = 40;
    int const HOURS_IN_WORK_DAY = 8;

    //Declare Variables
    int employeeName;
    int hoursWorked;
    int totalWeeksWorked;
    int leftoverFromWeeks;
    int totalDaysWorked;
    int leftoverFromDays;
    int totalHoursWorked;


    //Get Input
    cout << "enter employee name: ";
    cin >> employeeName;

    cout << "Enter total hours worked: ";
    cin >> hoursWorked;


    //calculate total weeks, days, and hours worked
    totalWeeksWorked = hoursWorked / HOURS_IN_WORK_WEEK;
    leftoverFromWeeks = hoursWorked % HOURS_IN_WORK_WEEK;

    totalDaysWorked = leftoverFromWeeks / HOURS_IN_WORK_DAY;
    leftoverFromDays = leftoverFromWeeks % HOURS_IN_WORK_DAY;

    totalHoursWorked = leftoverFromDays;

    //Output
    cout << employeeName << "worked " << hoursWorked << "hours or " << totalWeeksWorked << "week(s), " << totalDaysWorked << "day(s), and " << totalHoursWorked << "hours.";






    system("pause");


}//End Main

1 个答案:

答案 0 :(得分:3)

我认为发生的事情是你在不知不觉中为员工的姓名输入了一个字符串。但是,如果你看一下你的宣言:

int employeeName;

变量的类型是int!将其更改为std::string并使用getline读取以空格分隔的全名(std::cin将停止在空格处读取,这意味着其余输入将尝试存储在{{ 1}},导致第一个变量发生的相同行为。)

输入代码现在将更改为:

int

另外,在旁注中,您应该阅读为什么使用cout << "enter employee name: "; getline(cin, employeeName); not a good idea(虽然这对于这么小的程序并不重要,但它是有用的知识)。