gpt4 book ai didi

c - 通过结构数组搜索用户输入的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:42 25 4
gpt4 key购买 nike

这只是我程序中的一个函数,它应该搜索用户在结构数组中输入的字符串或整数。我想要做的是添加一条错误消息,并在结构数组中找不到输入的字符串或整数时重试。如果您输入正确的字符串或整数,它会搜索得很好,但如果您不输入,则什么也不会发生。我正在尝试改变它,但找不到解决方案。

我已经尝试了一段时间,在我的 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++;
}
}

最佳答案

也许这可以帮助

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;

关于c - 通过结构数组搜索用户输入的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46629738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com