我正在开发一个继承项目,其中DollarAmount是SpendingRecord类的父类。这两个输入函数似乎有问题,因为无论何时输入-1(分隔符),它都不会在main中输入if语句,因此程序永远不会中断并且它接受-1作为可接受的美元金额(它如果用户不再希望输入美元金额,则只应接受-1)。 getDollar,getCent和getDELIM是DollarAmount类的函数,所以我假设SpendingRecord继承了它们。有人可以帮忙吗?
void DollarAmount::inputDollar( istream &ins )
{
char decimal;
int dollar, cent;
cout << "\n$PrintDollar " << endl;
cout << "Enter the expenditure record (e.g., 1.95, coffee, enter -1 to end): $";
ins >> dollar;
if ( dollar != getDELIM())
{
ins >> decimal >> cent;
}
//
//check to make sure that the user inputs the correct amount
//ensures that dollar is in between 0 and 9999
//ensures that the user does not put 0 dollars and 0 cents
//ensures that the cents amount is between 0 and 99
//
while ( !setCent(cent) || !setDollar(dollar) || dollar == 0 && cent == 0 && dollar != getDELIM())
{
cout << "Invalid dollar/cent amount, please reenter: $";
ins >> dollar >> decimal >> cent;
}
while( ins.fail() ){
ins.clear();
ins.ignore(1000,'\n');
cout << "Wrong input types, please reenter: $";
ins >> dollar >> decimal >> cent;
}
setDollar(dollar);
setCent(cent);
}
void SpendingRecord::inputDollar( istream & in )
{
string itemName;
DollarAmount::inputDollar(in);
if ( dollar != getDELIM() )
{
in >> itemName;
getline( in, itemName );
SpendingRecord::itemName = itemName;
}
}
//in main
SpendingRecord *ptr = NULL;
ptr = new SpendingRecord[MAX];
for ( int i = 0; i < psize; i++ )
{
cin >> ptr[i];
//
//if user has put in the last element of the array
//allocate a new array of a larger size and set it to NULL
//copy the contents of smaller array into larger array
//delete the old array
//assign address location of new array to older array
//increase the physical size of the array
//
if ( i == psize - 1 )
{
SpendingRecord *tmp = NULL;
tmp = new SpendingRecord[psize*2];
for ( int j = 0; j < psize; j++ )
tmp[i] = ptr[i];
delete [] ptr;
ptr = tmp;
psize *= 2;
}
//if the user enters -1, break and do not include the last element ( i.e. -1 ). The program does not seem to enter this break statement
if ( ptr[i].getDollar() == getDELIM() && ptr[i].getCent() == 0 )
{
numElements = i;
break;
}
}
答案 0 :(得分:0)
什么类型返回函数getDELIM()
?应该是int
,因为我希望避免溢出。无论如何,它在哪个循环中无限?
对我来说,循环中的条件
while (!setCent(cent) || !setDollar(dollar) || dollar == 0 && cent == 0 && dollar != getDELIM())
{ cout << "Invalid dollar/cent amount, please reenter: $"; }
看起来很奇怪,评论对我来说更具可读性。我想当值小于零时,setCent()
可能会返回false。
我认为你在这种情况下缺少括号。
根据它我会写这个:
while ((!setCent(cent) || !setDollar(dollar)) || (dollar == 0 && cent == 0) || dollar != getDELIM())
{...}