Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

How to stop and get exact result from For loop in C language

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("%[^
]s", batas[0].nim);
    printf("TEST2 : "); scanf(" %[^
]s", batas[1].nim);
    printf("TEST3 : "); scanf(" %[^
]s", batas[2].nim);
 
    char str[10];
    printf("TEST : "); scanf(" %[^
]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
", x);
    return 0;
}

Here, from the result of x always gets the FLAGXX result. I want to get the FLAG result here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

One typical algorithm would be to break the for loop when a match is found. (An explanation of break and the oppositionally related continuecan be found here, which happens to be the first google hit.)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...