gpt4 book ai didi

c++ - 什么是 cin.peek,它有什么作用?

转载 作者:行者123 更新时间:2023-11-30 04:54:41 24 4
gpt4 key购买 nike

#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;
}
}

谁能解释一下上面代码中的 cin.peek 语句及其作用? EOF|| 如何cin.peek() == '\n') 影响这个。

当我输入浮点值时,第一个 else 值激活,但结果仍然显示。如何调整代码以使总费用不出现?

最佳答案

输入流上的“peek”函数(在您的例子中是 cin)从流中检索下一个字符而不实际使用它。这意味着您可以“预览”输入中的下一个字符,并在下一次调用任何消耗操作(重载的 operator >>cin.read)时读取那个角色并消耗它。

条件 eof() || cin.peek == '\n' 检查是否到达输入文件流的末尾或者用户是否提供了换行符。

关于您的其他问题:如果输入无效(例如浮点值),您不会退出该函数。因此,您继续执行并打印值。只需使用 return 1; 退出函数即可。

关于c++ - 什么是 cin.peek,它有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53451531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com