我已经编辑了这个问题,因为该解决方案没有按我的预期工作。是否可以编写某种 if 语句或任何其他代码,当输入的字符串不存在于该结构数组中时打印出错误消息?打印出错误消息后,它会再次请求该字符串。我已经尝试了一段时间了,但似乎无法成功。
int ordet=0; char_sokafras[20];
printf("Name?\n");
scanf("%s", soka_fras);
while(ordet<*num_items)
{
if(strstr(varor[ordet].name, soka_fras))
{
printf("Name found!\n");
soka[hitta_tecken]=varor[ordet];
hitta_tecken+=1;
}
ordet+=1;
}
最佳答案
strstr
返回指向 haystack 中子字符串开头的指针。来自联机帮助页:
If needle is an empty string, haystack is returned; if needle occurs nowhere in haystack, NULL is returned; otherwise a pointer to the first character of the first occurrence of needle is returned.
将 while 循环修改为这样应该就足够了:
while (strstr(varor[i].name, soka_fras) != NULL)
关于c - 在结构体数组中搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46621298/