我遇到了陷入getIntLimited函数的问题。在adjustQuantity中,我需要它来检查用户是否输入了正确的数字,而不是更多或更少,而不是字母。我没有那样做“股票”选项,只在“检查”选项中。但我的第一个问题是我必须输入两次数字才能得到响应,第二个问题是我无法退出getIntLimited循环。 这是输出的图像:
和我的代码部分:
void GroceryInventorySystem(void){
struct Item Items[MAX_ITEM_NO];
int opt, records;
int loop = 0;
welcome();
while(!loop){
if(opt == 3){
adjustQuantity(Items, records, CHECKOUT);
saveItems(Items, DATAFILE, records);
if(0 == saveItems(Items, DATAFILE, records)){
printf("Could not update data file %s\n", DATAFILE);
}
pause();
}
}
int getInt(void){ // Check if user entered the character and breaks, returns the value if a number //
char letter = 'x';
int value;
while(1){
scanf("%d%c", &value, &letter);
if(letter != '\n'){
printf("Invalid integer, please try again: ");
flushKeyboard();
}else{
return value;
}
}
}
int getIntLimited(int lowerLimit, int upperLimit){ // Check if user typed the value higher/lower and repeats. Returns the value if user entered the right number //
int Value;
while(1){
Value = getInt();
if(Value <= lowerLimit || Value >= upperLimit){
printf("Invalid value, %d < value < %d: ", lowerLimit, upperLimit);
}else{
return Value;
}
}
}
void adjustQuantity(struct Item item[], int NoOfRecs, int stock) {
int check, sku, index, opt;
char tostock[] = "to stock", tocheck[] = "to checkout";
printf("Please enter the SKU: ");
scanf("%d", &sku);
check = locateItem(item, NoOfRecs, sku, &index);
if (check == 0) {
printf("Item not found!\n");
} else {
displayItem(item[index], FORM);
if (stock == STOCK) {
printf("Please enter the quantity %s; Maximum of %d or 0 to abort: ", tostock, MAX_QTY - item[index].quantity);
scanf("%d", &opt);
if (opt == 0) {
printf("--== Aborted! ==--\n");
} else {
item[index].quantity += opt;
printf("--== Stocked! ==--\n");
}
} else {
printf("Please enter the quantity %s; Maximum of %d or 0 to abort: ", tocheck, item[index].quantity);
scanf("%d", &opt);
if (opt == 0) {
printf("--== Aborted! ==--\n");
} else if (item[index].quantity < opt){
opt = getIntLimited(item[index].quantity, 0);
} else {
item[index].quantity -= opt;
printf("--== Checked out! ==--\n");
if (item[index].quantity <= opt) {
printf("Quantity is low, please reorder ASAP!!!\n");
}
}
}
}
}
答案 0 :(得分:0)
我在opt = getIntLimited(0, item[index].quantity);
中犯了一个错误,它应该与此opt = getIntLimited(item[index].quantity, 0);
相反,现在只要我在0到5之间键入正确的数字,它就会退出循环。
我还推出了opt = getIntLimited(0, item[index].quantity);
而不是scanf
,并删除了其他if语句