当我输入一个十进制数量的员工时,它输出“请输入至少1的值”无限次。但是小数不应该被截断吗?我如何解决这个问题,以便删除小数。这种情况发生在几天的输入中。
#include <iomanip>
#include <iostream>
using namespace std;
int getNumEmployees();
int getDaysMissed(int);
double getAverageDays(int,int);
int main()
{
int numEmployees;
int daysMissed;
double average;
//Get the number of employees
numEmployees = getNumEmployees();
//Get the number of days missed
daysMissed = getDaysMissed(numEmployees);
//Get the average days missed
average = getAverageDays(numEmployees, daysMissed);
cout << "The average number of days missed is: " << average << endl;
system("pause");
return 0;
}
int getNumEmployees()
{
int employeeNum;
cout << "Enter the number of company employees: ";
cin >> employeeNum;
while(employeeNum < 1)
{
cout << "Please enter a value of atleast 1 " << endl;
cin >> employeeNum;
}
return employeeNum;
}
int getDaysMissed(int employeeNum)
{
int totalDays = 0;
int employee;
for(int count = 1; count <= employeeNum; count++)
{
cout << "Enter the number of days employee " << count << " missed: ";
cin >> employee;
while(employee < 0)
{
cout << "Enter a positive number for days missed " << endl;
cin >> employee;
}
totalDays += employee;
}
return totalDays;
}
double getAverageDays(int employeeNum, int totalDays)
{
double averageDays;
averageDays = totalDays / employeeNum;
return averageDays;
}
答案 0 :(得分:2)
每次成功完成cin
操作后,您需要使用:
cin.clear();
重置失败标志 然后使用:
cin.ignore();
忽略刚刚导致错误的字符串,因此您不会再尝试解析它。
你应该做的事情如下:
int employeeNum = 0;
cout << "Enter the number of company employees: ";
while (!(cin >> employeeNum) || employeeNum < 1)
{
if(cin.fail())
{
cout << endl << "Please enter a valid value: ";
cin.clear (); // reset the "failure" flag
}
else if(employeeNum < 1)
{
cout << "Please enter a value of at least 1: ";
}
// ignore the bad charactors
// needed here incase '0.XX was entered
cin.ignore(10000, '\n');
}
如果输入的值是小数,则小数将被截断,而不是舍入。
ignore
的默认值是只跳过1个字符,但是如果你希望得到一个很长的无效字符串(比如小小数:0.23),你应该将ignore
更改为:< / p>
cin.ignore(10000, '\n')
最多可跳过10000个字符或直到下一个换行符。
答案 1 :(得分:2)
int employeeNum;
cin >> employeeNum;
此代码尝试从int
解析std::cin
。首先,您事后并未实际检查流状态 - 您认为employeeNum < 1
充分传达了故障,但这通常不是最佳方法:输入流上可能存在EOF或错误情况。对于前者,您的程序可能需要终止,对于后者,您可能希望忽略该输入行的其余部分并在重试之前清除错误条件:
#include <limits>
if (std::cin >> employeeNum)
break; // no need to retry input...
else if (std::cin.eof())
throw std::runtime_error("EOF on input");
else
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n').clear();
但是小数不应该被截断吗?我如何解决这个问题,以便删除小数。
如果要输入实数,然后使用其“截断”值,则需要输入double
或float
,然后将其转换为代码中的int
。假设您不需要范围检查......
double x;
if (std::cin >> x)
{
int x_int = x;
...use x_int...
}