【问题标题】:How to stop and get exact result from For loop in C language如何停止并从 C 语言中的 For 循环中获得准确的结果
【发布时间】: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 输出)
  • 获得准确结果的最佳方法是不要用不准确的结果覆盖它。

标签: c loops for-loop struct


【解决方案1】:

获得准确结果的最佳方法是不要用不准确的结果覆盖它。如果其中一个字符串匹配,您希望 x 包含“FLAG”;但除非是最后一次循环迭代,否则x 将在稍后遇到不匹配时被覆盖。

当找到匹配项时,一个典型的算法是break for 循环。 (break 和与之相反的continue 的解释可以在here 找到,这恰好是谷歌的第一个热门。)

我还建议简单地使用一个布尔标志,当进入循环时该标志为假,找到匹配项时设置为真;没有理由在每次迭代期间复制字符串(以及相同的字符串!)。

【讨论】:

  • 谢谢彼得,现在解决了,只需要break 就可以从循环中停止
猜你喜欢
  • 2018-11-28
  • 2022-01-17
  • 2022-01-11
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
  • 2011-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多