C / C ++的预期行为 [英] A expected behavior of C/C++

查看:98
本文介绍了C / C ++的预期行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个人都好......

我有一个 C / C ++ 程序。当我运行这段代码时,程序的行为很奇怪。



我尝试了什么:



Hellow every one...
I have a C/C++ program. And when i run this code the behavior of program is very odd.

What I have tried:

#include "stdafx.h"
#include "iostream"
using namespace std;

int main() {
	int n;

	do {
		cout << "Enter a number   = ";
		cin >> n;
	} while (n != 2);
}







编译此代码为并输入一个整数值,但代码工作2除外好吧。

现在输入字符浮点(非整数)数字,看看奇怪的行为。

无论你使用for,while还是do-while循环,行为都是一样的。

我在 visual studio 2012,2013,2015 turbo中尝试了这段代码C 3.1 版本。行为是一样的。



所以任何人都可以帮我解决这个问题。




Compile This code is and enter a integer value except 2 the code works well.
Now enter a character or a float (not integer) number and see the odd behavior.
No matter you use for, while or do-while loop the behavior is the same.
I tried this code in visual studio 2012, 2013, 2015 and turbo C 3.1 versions. The behavior is same.

So can any one help me in to solve this problem.

推荐答案

简短的回答是,在检测到无效输入时, cin (这是一个 istream )设置其失败状态位,导致进一步的输入被忽略,直到流的错误被清除。这根本不是意料之外的。它永远属于标准行为的一部分。
The short answer is that, on detecting invalid input, cin (which is an istream) sets its fail status bit, causing further input to be ignored until the stream's error is cleared. This is not unexpected at all. It's been part of the standard behaviour since forever.


这篇关于C / C ++的预期行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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