这只是我的程序中的一个函数,它应该搜索用户在struct数组中输入的字符串或整数。我尝试做的是添加一条错误消息,并在结构数组中找不到输入的字符串或整数时再次尝试。如果输入正确的字符串或整数,它会搜索得很好,但如果你没有,则没有任何反应。我试图改变它,但无法找到解决方案。
我已经尝试了一段时间,其中一个案例在我的switch语句中,但我需要为这三个案例执行此操作。但到目前为止,我只尝试过案例3.
search(struct items aItems[], int *num_items)
{
int choice_of_search, b=0, found_word=0, search_num, i=0, j=0, k=0;
char search_phrase[20]; struct items search[MAX];
printf("Choose what to search for? (1) Item number, (2) Name and (3) Balance. ");
scanf("%d", &choice_of_search);
while(choice_of_search < 1 || choice_of_search > 3)
{
printf("Wrong choice!\n");
printf("Choose what to search for? (1) Item number, (2) Name and (3) Balance. ");
scanf("%d", &choice_of_search);
}
switch(choice_of_search)
{
case 1:
printf("Item number?\n");
scanf("%d", &search_num);
for(i = 0; i < *num_items; i++)
{
if(search_num == aItems[i].itemnumber)
{
printf("Item number found!\n");
search[found_word]=aItems[i];
found_word+=1;
}
}
break;
case 2:
printf("Name?\n");
scanf("%s", search_phrase);
for(i = 0; i < *num_items; i++)
{
if(strstr(aItems[i].name, search_phrase))
{
printf("Name found!\n");
search[found_word]=aItems[i];
found_word+=1;
}
}
break;
case 3:
printf("Balance?\n");
scanf("%d", &search_num);
for(i = 0; i < *num_items; i++)
{
if(search_num == aItems[i].balance)
{
printf("Balance found!\n");
search[found_word]=aItems[i];
found_word+=1;
}
else
{
printf("Balance not found! Try again.\n");
printf("Balance?\n");
scanf("%d", &search_num);
}
}
break;
}
while(b < found_word)
{
printf("Item number: %d Name: %s Balance: %d\n", search[b].itemnumber, search[b].name, search[b].balance);
b++;
}
}
答案 0 :(得分:3)
也许这可以帮助
int done;
...
...
case 3:
done = 0;
while(1);
{
printf("Balance?\n");
scanf("%d", &search_num);
for(i = 0; i < *num_items; i++)
{
if(search_num == aItems[i].balance)
{
printf("Balance found!\n");
search[found_word]=aItems[i];
found_word+=1;
done = 1;
}
}
if (done) break;
printf("Balance not found! Try again.\n");
}
break;
但请注意,代码不是用户友好的,因为它不允许用户在没有匹配的情况下停止搜索。所以也许你应该考虑添加一个“你想再试一次”选项。
一种简单的方法可能是
printf("Balance not found! Would like to try again?.\n");
scanf(" %c", &some_char);
if (some_char != 'y') break;