c - 在结构体数组中搜索字符串

标签 c arrays string struct

我已经编辑了这个问题,因为该解决方案没有按我的预期工作。是否可以编写某种 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/

相关文章:

javascript - 在 JavaScript 中用随机数创建长度为 n 的数组

c# - 为什么我可以将空条件运算符应用于硬编码字符串?

java - 'messy'字符串到int转换java

c - 如何使用冒泡排序对二维数组进行排序?

c - 如何计算C中两组之间的差异?

c - 连续发送两个缓冲区

java - Hashtable<String,Integer[]> myhash = new Hashtable();

c - 在 C 中取消引用指针数组

java - setfill() 和 setw() Java 等效?

c - yacc 错误 : '' x' has no declared type