#include <iostream>
using namespace std;
int main()
{
//Declare data types
int NumChild; //var
const int BaseFee = 150; //constant
//Welcome + Instructions for users
cout << "Welcome to IOU Secondary School" << endl <<endl<< "How many
children are attending the school this year? "<<endl;
//Nested IF-ELSE (error checking)
if (cin >> NumChild)/
{
//do not accept any non-integer values
if (cin.peek() == EOF|| cin.peek() == '\n' )
{
}
else
{
cout <<endl<< "Error: enter a whole number."<<endl<< "The total
amount below represents the initial number entered e.g. if 5.7 is entered, the fee will be calculated according to 5 children" << endl;//error message for float entry
cin.ignore(100, '\n'); //read and discard up to 100 characters from the input buffer, or until a newline is read
cin.clear();//resets any error flags in the cin stream
}
}
else
{
// Edit: You should probably also clear the steam
cin.ignore(100, '\n');//read and discard up to 100 characters from
the input buffer, or until a newline is read
cin.clear(); //resets any error flags in the cin stream
cout << "Error: Restart the program and enter a number";
}
//nested IF statement (Calculation of fees)
if(NumChild == 1) //1 child attending
{
cout<<endl<<"The total cost of your child's fees are $"<< BaseFee+50 <<
endl;
}
if(NumChild == 2) //2 children attending
{
cout<<endl<<"The total cost of your children's fees are $"<< (BaseFee*2)+85
<< endl;
}
if(NumChild == 3)//3 children attending
{
cout<<endl<<"The total cost of your children's fees are $"<< (BaseFee*3)+110
<< endl;
}
if(NumChild > 3) //More than children attending
{
cout<<endl<<"The total cost of your children's fees are $"<<
(BaseFee*NumChild)+150 << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释上面代码中的 cin.peek 语句及其作用吗?对这个有什么EOF|| cin.peek() == '\n')影响。
当我输入浮点值时,第一个 else 值会激活,但结果仍然显示。如何调整代码以使总费用不出现?
输入流上的“peek”函数(在您的情况下cin)从流中检索下一个字符,而不实际消耗它。这意味着您可以“预览”输入中的下一个字符,并且在下次调用任何使用操作(重载operator >>或cin.read)时将读取该字符并使用它。
该条件eof() || cin.peek == '\n'检查是否到达输入文件流的末尾或者用户是否提供了换行符。
关于您的其他问题:如果输入无效(例如浮点值),您不会退出该函数。因此,您继续执行并打印该值。只需使用 退出该函数即可return 1;。