我在卡在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");
}
}
}
}
}
最佳答案
我在opt = getIntLimited(0, item[index].quantity);
中犯了一个错误,应该像这样的opt = getIntLimited(item[index].quantity, 0);
相反,现在只要我在0到5之间输入正确的数字,它就会退出循环。
我还放了opt = getIntLimited(0, item[index].quantity);
而不是scanf
,并删除了if语句
关于c - 卡在getIntLimited函数中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43329333/