C语言将查找姓名的for循环改写为找到目标即终止的while循环
问题原因
你写的while循环无法提前终止的核心问题是匹配到目标后没有主动终止循环的逻辑,哪怕已经找到对应姓名,循环还是会继续遍历剩下的元素,直到计数器i超出范围才会停止。另外你原有的for循环本身也存在同样的问题,不是只有while循环有这个缺陷。
修正后完整代码
#include <stdio.h> #include <string.h> int main() { char *name[] = {"Peter", "Mary", "John", "Bob", "Kathy"}; char target_name[10]; int i = 0, position = -1; printf("Enter a name to be searched: "); // 修正原写法多余的&,target_name本身就是数组首地址 scanf("%s", target_name); while (i <= 4) { if (strcmp(target_name, name[i]) == 0) { position = i; // 匹配成功直接跳出循环,无需遍历后续元素 break; } i++; } if (position >= 0) printf("%s matches the name at index %d of the array.\n", target_name, position); else printf("%s is not found in the array.", target_name); return 0; }
关键修改点
- 匹配到目标姓名后新增
break语句,直接终止while循环,最多遍历到匹配位置就停止,不需要走完所有5个元素 - 调整了分支的大括号和缩进,避免逻辑歧义:原来的
i++和if判断平级,不管是否匹配都会自增,调整后逻辑更清晰 - 修正了两处语法隐患:原代码
i = 0,的逗号改为分号、scanf("%s", &target_name)的取地址符&删除(数组名本身就是首地址,加&属于错误用法)
内容的提问来源于stack exchange,提问作者the-great-potato
相关产品推荐
相关产品推荐

