谁能告诉我为什么这会两次提示?

时间:2014-09-12 17:53:43

标签: c++ if-statement

我想进行两次检查,以确保在提示用户时,我会收到一些输入。然后用户将检查该输入是否小于或等于1000.而是提示两次..

#include <iostream>
#include <string> 
using namespace std;

int die( const string & msg ){
cout <<"Fatal error: " <<msg <<endl;
exit( EXIT_FAILURE );
} // die 

int main(){
unsigned q, d, n, p, cents; // quarters, dimes, nickels, pennies
cout <<"Quarters (Less than 1000)? " <<endl; 
cin >>q;
if ( q >= 1000 || !( cin>>q ) ) die( "Input failure" );
  cout <<"Dimes (Less than 1000)? " <<endl;
  cin >>d;
if ( d >= 1000 || !( cin>>d ) ) die( "Input failure" );
  cout <<"How many Nickels? (Less than 1000) " <<endl; 
  cin >>n;
if ( n >= 1000 || !( cin>>n ) ) die( "Input failure" );
  cout <<"How many Pennies? (Less than 1000) " <<endl; 
  cin >>p;
if ( p >= 1000 || !( cin>>p ) ) die( "Input failure" );
  cents = (q*25)+(d*10)+(n*5)+p;
  cout <<"That's " <<cents <<" cents!" <<endl;
} // main

我是否正确使用了if-else?

2 个答案:

答案 0 :(得分:0)

您正在读取每个变量两次,仅测试第二次读取是否成功。

您可以删除未经检查的读取并重新排列条件:

cout <<"Quarters (Less than 1000)? " <<endl; 
if ( !(cin >> q) || q >= 1000 ) die( "Input failure" );

这将首先尝试读入q,并且只有在读取成功时才检查其值。

答案 1 :(得分:0)

至少有你想要的方法:
1)在任何点输入故障,导致该输入周围的循环 2)任何时候输入失败,导致重启。

检查每个输入的情况如下:

int quarter_quantity = 0;
do
{
  quarter_quantity = -1;
  if (cin >> quarter_quantity)
  {
    if ((quarter_quantity >= 0) && (quarter_quantity < 1000))
    {
       break;
    }
  }
  else
  {
     die();
  }
} while (quarter_quantity >= 0);

在类似的上下文中,您可以让程序循环,直到所有硬币数量都有效。

相关问题