关于std :: cin的怪异问题 [英] a weird problem about std::cin

查看:106
本文介绍了关于std :: cin的怪异问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
using namespace std;

int main()
{
        // variable declaration and intialisation
	int length1 = 0, length2 = 0;

	// get Input One
	cout << "Enter the length of the first line in the form MMMCC: ";
	cin >> length1;
	
	// verify Input One
	if (length1 < 10000 || length1 > 99999)
	{
		cout << "A wrong input!" << endl;
		return 1;
	}

	// get Input Two
	cout << "\nEnter the length of the second line in the form MMMCC: ";
	cin >> length2;

	// verify Input Two
	if (length2 < 10000 || length2 > 99999)
	{
		cout << "A wrong input!" << endl;
		return 1;
	}

	// compute the sum and output it
	cout << "\nThe sum is: " << length1 + length2 << endl;

	return 0;
}


我的意思是要计算2个整数的总和,同时也可以输入小数.显然,小数将被简单地切成整数.但是奇怪的是,当我在输入一"中输入小数时,结果变得难以理解.你们可以试试看.顺便说一下,我在VS2008中编码.
谢谢.


I do mean to compute the sum of 2 integers while input of decimals is also possible. It is obvious that the decimals will be simply cut into an integer. But what is odd is that when I input a decimal in Input One, the result turns to be difficult to understand. You guys can have a try. By the way I''m coding in VS2008.
Thanks.

推荐答案

问题出在cin处理输入字段的方式上.由于期望整数,它将读取句点字符并将其作为整数返回.流中的下一个字符是句点,它不是有效的整数,因此它将返回零,并且由于该值不符合您的条件,因此程序将失败.我建议使用调试器单步执行程序,以准确了解每一步收到的值.
The problem is with the way cin handles input fields. Since it is expecting an integer it will read up to the period character and return that as an integer. The next character in the stream is the period which is not a valid integer so it will return zero, and since the value does not match your criteria, your program will fail. I would suggest single stepping through your program with the debugger to see exactly what values you receive at each step.


谁告诉您很显然,小数将被简单地切成整数" ?这不是真的.首先,不清楚小数"的含义(因为整数也为十进制),但看起来您的意思是任何数字类型的数量",包括小数,浮点数或其他任何数字.

否.如果您声明整数,则程序将使用整数数字格式,而别无其他.如果不是这样,结果通常是不可预测的.输入流不会显示不自然的智力".

—SA
Who told you that "obvious that the decimals will be simply cut into an integer"? This is not true. First of all, it''s not clear what do you mean by "decimal" (as integer is decimal, too), but it looks like you mean "number of any numeric type", including fractional, floating-point or whatever.

No. If you declare integer, the program expect integer numeric format and nothing else. If it is not, result is generally unpredictable. Input streams do not demonstrate "unnatural intellect".

—SA


这篇关于关于std :: cin的怪异问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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