cin.eof()功能 [英] cin.eof() functionality

查看:82
本文介绍了cin.eof()功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道cin.eof()测试流格式.并且在输入时,如果输入错误,则不会到达字符结束.我在 MSV C ++ 2010 上对此进行了测试,但并不理解奇怪的结果.无论我提供什么输入,我都会收到程序中出现的 Format Error 消息.

I understand that cin.eof() tests the stream format. And while giving input, end of character is not reached when there is wrong in the input. I tested this on my MSV C++ 2010 and am not understanding the strange results. No matter what I give the input, I am getting Format Error message that is present in the program.

#include <iostream>
using namespace std;

int main()
{
    int i;
    cin>> i;

    if(!cin.eof())
    {
        cout<< "\n Format Error \n";
    }
    else
    {
        cout<< "\n Correct Input \n";
    }

    getchar();
    return 0;
}

我期望的结果:

i的值=

  1. 10 => 正确的输入,但输出为格式错误
  2. 12a => 格式错误
  1. 10 => Correct Input but the output is Format Error
  2. 12a => Format Error

有人可以解释我要去哪里.谢谢.

Could someone explain where I am going wrong. Thanks.

推荐答案

std::cin.eof()测试 文件结束 (因此为eof),而不是错误.对于错误检查,请使用!std::cin.good(),内置转换运算符(if(std::cin))或布尔求反运算符(if(!std::cin)).

std::cin.eof() tests for end-of-file (hence eof), not for errors. For error checking use !std::cin.good(), the built-in conversion operator (if(std::cin)) or the boolean negation operator (if(!std::cin)).

这篇关于cin.eof()功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆