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

时间:2018-11-23 18:34:46

标签: c++ iostream cin

#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值会激活,但结果仍然显示。如何修改代码以使总费用不显示?

2 个答案:

答案 0 :(得分:1)

输入流中的“窥视”功能(在您的情况下为“ cin”)从流中检索下一个字符,而无需实际使用。这意味着您可以“预览”输入中的下一个字符,并且在下次调用任何消耗操作(重载运算符>>或cin.read)时,将读取该字符并将其消耗。

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

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

答案 1 :(得分:0)

peek looks at a character without removing it from the stream。该代码将检查以确保流中的下一个字符是文件的末尾或行的末尾,而不会从流中提取字符并损坏后续的有效输入。

它不能接受浮点数,因为cin >> NumChild会读取int并在达到小数点后立即停止。示例:输入“ 3.14”。 numChild将包含3。流中仍保留“ .14”,因此peek将读取'.',而不是文件末尾或换行符,并显示错误消息。

然后继续执行该程序的其余部分,因为没有任何内容告知它停止。您需要围绕输入循环,以继续请求更多输入,直到提供有效输入为止。

一个简单的例子:

bool goodInput = false;
while (!goodInput)
{
    your code here
    if (cin.peek() == EOF|| cin.peek() == '\n' )
    {
        goodInput = true; // change made here
    } 
    your code here
}