【发布时间】:2021-01-23 11:17:37
【问题描述】:
如何从for 循环中退出,因为我的代码总是从for 循环中获取最新结果?我的for 循环条件有什么问题?这是我的代码:
#include <stdio.h>
#include <string.h>
int main(){
int i, n = 3, a;
char x[20];
struct data {
char nim[10];
};
struct data batas[100];
printf("TEST1 : "); scanf("%[^\n]s", batas[0].nim);
printf("TEST2 : "); scanf(" %[^\n]s", batas[1].nim);
printf("TEST3 : "); scanf(" %[^\n]s", batas[2].nim);
char str[10];
printf("TEST : "); scanf(" %[^\n]s", str);
for(i=0; i<n; i++){
if (strcmp(str, batas[i].nim) == 0) {
puts("Value exist");
strcpy(x, "FLAG");
} else {
puts("Value doesn't exist");
strcpy(x, "FLAGXX");
}
}
printf("%s\n", x);
return 0;
}
这里,从x 的结果总是得到FLAGXX 结果。我想在这里得到FLAG 的结果。
【问题讨论】:
-
"%[^\n]s"->"%[^\n]" -
找到值后,设置标志并退出循环,否则下一次循环运行将检查不存在的值。
-
这个循环的结构首先是错误的。默认值(即不匹配)应设置在 before 循环之前,并且循环应在内部主体(
if)测试为 true 之后break;设置为FLAG。跨度> -
在循环之前用“FLAGXX”初始化,只是不要在循环内用“FLAGXX”覆盖。 (假设您确实想要每个元素的
Value exist/Value doesn't exist输出) -
获得准确结果的最佳方法是不要用不准确的结果覆盖它。