【问题标题】:For-loop exeeds condition limit in CFor-loop 超出 C 中的条件限制
【发布时间】:2013-11-12 12:45:06
【问题描述】:

在我的输出中一切都很好,除了它需要一个 NULL 字符是正确的,错误是在 for 循环检查数组 *ans[]={"zero","one","two"};inp 之间的条件之后:@ 的最后一个数字987654323@ 是2 并且在我的条件仍然为真的情况下它执行sel++ 这使得sel = 3 这是我的限制,导致NULL 输入被接受。 我将如何限制 sel 在我的 for 循环中超出其限制?

#include <stdio.h>
#include <conio.h>
#include <string.h>

void main(){
    char    inp[256]={0},
            *ans[]={"zero","one","two"};
    int     sel,
            ans_cnt=sizeof(ans)/sizeof(ans[0]); // Equals to 3
    do{
        clrscr();
        printf("Enter Any:\n\"zero\" or \n\"one\"  or \n\"three\": ");
        gets(inp);
        for(sel=0;sel<ans_cnt && strcmp(inp,ans[sel]);sel++);
        }
    while(strcmp(inp,ans[sel]));
    printf("Valid Answer!");
    getch();
    }

【问题讨论】:

  • 不要使用gets 函数,它已经被弃用了很长时间。请改用fgets
  • 好吧好吧。在这里(并停止使用gets()):while(sel == ans_cnt);

标签: c for-loop


【解决方案1】:

问题是,如果在内部for 循环中找不到字符串,那么sel 将是3。这会导致以下while 条件中的ans 被索引超出范围。

这可以通过更改 while 条件来解决:

while (sel == ans_cnt);

【讨论】:

  • 我也已经解释过了,但是越界这个词更好
  • @Daniel 应该是吗?它不在您的 ans 数组中。
【解决方案2】:

你可以使用 break 来代替它。

while ( TRUE ) {
  clrscr();
  printf("Enter Any:\n\"zero\" or \n\"one\"  or \n\"three\": ");
  gets(inp);
  for(sel=0;sel<ans_cnt && strcmp(inp,ans[sel]);sel++);
  if ( sel < 3 ) // It means for loop was ended before the sel < ans_cnt condition
    break;
}

【讨论】:

  • 很多人建议不要只使用while循环,因为我的原始代码有多个条件......
  • @Daniel 你仍然可以使用 break 和 do...while();
猜你喜欢
  • 2011-03-02
  • 2019-08-09
  • 1970-01-01
  • 1970-01-01
  • 2018-02-24
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多