简体   繁体   English

在结构数组中搜索字符串

[英]Searching for string in struct array

I've edited the question since the solution didn't work as intended for me. 由于解决方案无法满足我的要求,因此我已经编辑了问题。 Is it possible to write some sort of if statement or any other code for that matter, that prints out an error message when the entered string does not exist in that struct array ? 是否有可能为此编写某种if语句或任何其他代码,当所输入的字符串在该struct数组中不存在时打印出错误消息? After it prints out an error message, it asks for the string again. 打印出错误消息后,它将再次要求输入字符串。 I've tried for a while now and can't seem to get it right. 我已经尝试了一段时间,但似乎无法正确解决。

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 returns a pointer to the start of the substring in haystack. strstr返回一个指向干草堆中子字符串开头的指针。 From manpages: 从手册页:

If needle is an empty string, haystack is returned; 如果needle是一个空字符串,则返回干草堆。 if needle occurs nowhere in haystack, NULL is returned; 如果针在干草堆中无处发生,则返回NULL;否则返回NULL。 otherwise a pointer to the first character of the first occurrence of needle is returned. 否则,返回指向第一次出现needle的第一个字符的指针。

Amending the while loop to this should be enough: 修改while循环到此应该足够了:

while (strstr(varor[i].name, soka_fras) != NULL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM