如何在C语言中从For循环停止并获取确切结果 [英] How to stop and get exact result from For loop in C language
问题描述
如何从 for
循环中退出,因为我的代码总是从 for
循环中获取最新结果?我的 for
循环条件怎么了?这是我的代码:
How to get an exit from for
loop because my code always gets the latest result from the for
loop? What's wrong with my for
loop condition? This is my code:
#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
结果.
Here, from the result of x
always gets the FLAGXX
result. I want to get the FLAG
result here.
推荐答案
获得准确结果的最佳方法是不要用不精确的结果覆盖它.您希望x包含"FLAG"如果其中一个字符串被匹配;但除非是最后一次循环迭代,否则在遇到不匹配项时, x
会在以后被覆盖.
The best way to get the exact result is to not overwrite it with an inexact result. You want x to contain "FLAG" if one of the strings was matched; but unless it was the last loop iteration, x
will be overwritten later when a non-match is encountered.
一种典型的算法是在找到匹配项时 break
和与之相对应的 continue
的解释,请参见
One typical algorithm would be to break
the for loop when a match is found. (An explanation of break
and the oppositionally related continue
can be found here, which happens to be the first google hit.)
我还建议只使用一个布尔标志,当进入循环时该标志为假,当找到匹配项时设置为true.每次迭代时都没有理由在周围复制字符串(和相同的字符串!).
I would also recommend to simply use a boolean flag which is false when the loop is entered and set to true when a match is found; there is no reason to copy strings around (and the same string!) during every iteration.
这篇关于如何在C语言中从For循环停止并获取确切结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!