本文介绍了cin.fail()在C ++中的含义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

while (!correct)
    {

        cout << "Please enter an angle value => ";
        cin >> value; //request user to input a value

        if(cin.fail()) // LINE 7
        {
            cin.clear(); // LINE 9
            while(cin.get() != '\n'); // LINE 10
            textcolor(WHITE);
            cout << "Please enter a valid value. "<< endl;
            correct = false;

        }
        else
        {
            cin.ignore(); // LINE 18
            correct =true;
        }
    }

您好,这是我的代码的一部分书面。
此代码的目的是限制用户输入数字,如10,10.00等,
如果他们输入像(abc,!$ @等等)代码将请求用户重新输入

Hi, this is part of the code that I have written.The purpose of this code is to restrict users to input numbers like 10,10.00 etc,if they input values like (abc,!$@,etc...) the code will request users to reenter the values.

为了执行此功能(限制用户输入有效的valus),我通过论坛获得一些提示和指南。

In order to perform this function( restrict user to input valid valus), I get some tips and guides through forums.

我认为是我的责任,学习和理解这些代码做什么...因为这是我第一次使用这段代码。
有人可以简单地向我解释一下,
中的代码是7,9,10行,还是18行代码? 特别是第10行。我有一个简单的想法,其他线只是第10行我不知道它是做什么。

I think is my responsibility to learn and understand what these codes do... since this is the first time I use this code.can someone briefly explain to me what does the codes inline 7,9,10, and 18 do? Especially line 10. I got a brief idea on others line just line 10 I don't know what it did.

感谢您的指导,我感谢!

Thanks for your guides, I appreciate that!

推荐答案

cin.fail()在先前的输入操作中。我遗憾有一个输入流的四个已识别的状态: / code>和失败(但失败可以同时设置,例如)。

cin.fail() tells you if "something failed" in a previous input operation. I beleive there are four recognised states of an input stream: bad, good, eof and fail (but fail and bad can be set at the same time, for example).

cin.clear()将状态重置为 good

while(cin.get()!='\\\
');
电流输入线。

cin.ignore(); 将跳到下一个换行符,因此非常类似于 while(cin.get()!='\\\
');

cin.ignore(); will skip until the next newline, so is very similar to while(cin.get() != '\n');.

整个代码也应该检查文件结尾,否则如果没有给出正确的输入并且输入是结束,它将挂起例如取决于平台的CTRL-Z或CTRL-D)。

The whole code should check for end of file too, or it will hang (loop forever with failure) if no correct input is given and the input is "ended" (e.g. CTRL-Z or CTRL-D depending on platform).

这篇关于cin.fail()在C ++中的含义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 05:56