C++ primer plus第七单元课后习题第七题中cin无法进行光标输入

原程序如下:

#include<iostream>
using namespace std;
const int Max = 6;
double *fill_array(double *begin, double *end);
void show_array(double *begin, double *end);
double *revalue(double r, double *begin, double *end);

int main()
{
	double properties[Max];
	double *size = fill_array(properties, properties+Max);
	show_array(properties, size);
	cout << "Please enter the factor:" ;
	double factor;
	cin >> factor;
	revalue(factor, properties, size);
	show_array(properties, size);
	system("pause");
	return 0;
}

double *fill_array(double *begin, double *end)
{
	double temp;
	double *i = begin;     // 还是没有搞懂为什么直接把begin赋值给*i,按道理说如果不存在*i是一种数据类型
	int j = 0;             // 而是地址的话,那么这样确实解释得通,*i是数,而i是地址,double * 不是数据类型而是地址
	for (; i<end; i++)
	{
		cout << "enter the value #" << (j++ +1) << ":" ;
		cin >> temp;
		if (!cin || temp<0)
		{
			cin.clear();
			while (cin.get() != '\n');
			cout << "Bad input; Please enter a positive number(q to q): ";
			cin >> temp;
			if (!cin)
			{
				cout << "The input process terminated!" << endl;
				break;     
			}
		}
		*i = temp;
	}
	return i;
}

void show_array(double *begin, double *end)
{
	double *i = begin;
	for (; i<end; i++)
		cout << *i << endl;
}

double *revalue(double r,double *begin, double *end)
{
	double *i = begin;
	for (; i<end; i++)
	{
		*i *= r;
	}
	return i;
}

运行结果如下:

 

 要注意的代码段如下:

for (; i<end; i++)
    {
        cout << "enter the value #" << (j++ +1) << ":" ;
        cin >> temp;
        if (!cin || temp<0)
        {
            cin.clear();
            while (cin.get() != '\n');
            cout << "Bad input; Please enter a positive number(q to q): ";
            cin >> temp;
            if (!cin)
            {
                cout << "The input process terminated!" << endl;
                break;
            }

        }
        *i = temp;
    }
    return i;
}

在后面重新输入的q和空格输入之后一直留在缓冲队列中,所以cin在读取时直接读取的q,由于不是数字,所以程序出错。在代码中加入清除和把空格读取了之后才能继续进行有效输入。 

即:

if (!cin)
            {
                cout << "The input process terminated!" << endl;
                cin.clear();
                cin.get(); 
                break;  
            }

则运行结果如下:

 

话说为什么我觉得自己的代码那么复杂呢?脑子不够用吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值