0

我正在尝试编写一个简单的演示程序,该程序将在输入指定字符时跳出循环。我能够成功地做到这一点,直到我想添加我没有超过我的数组的额外条件。当我输入指定的字符时,这段代码不会跳出循环,我不知道为什么。代码的逻辑和设置似乎很合理!

#include <stdio.h>

char input[10];
char breakout = '!';
int idx;

int main(void)
{
printf("Input characters until %c character is used to break out", breakout);

for(idx = 0; input[idx] != breakout && idx < 10; idx++)
{
    scanf("%c", &input[idx]);
}

printf("Program terminated:");

getchar();
return 0;   
}

似乎 for 循环的条件在输入“!”时应该评估为假 性格,但事实并非如此。多谢你们

4

3 回答 3

2

您正在输入字符之前测试条件,如果您使用 do-while 循环,您可以在之后进行比较

idx = 0;
do
{
    scanf("%c\n", &input[idx]);
}
while( input[idx++] != breakout && idx < 10);
于 2013-10-20T02:25:30.687 回答
2

想想你的 for 循环条件。您input[idx]始终在查看数组中的下一个位置(尚不包含字符)——而不是从 scanf 调用接收到的前一个字符,该字符位于input[idx - 1]. 但是当然你不能检查input[idx - 1]第一次迭代,所以要小心。

for(idx = 0; (idx == 0 || input[idx - 1] != breakout) && idx < 10; idx++) 
{    
  ... 
}

出于或多或少的原因,超级复杂的 for 循环条件很少是一个好主意 -idx++迭代步骤发生在条件评估之前,它可能会令人困惑。在循环中使用 do/while 或中断条件。

于 2013-10-20T02:27:01.563 回答
1

您应该在输入字符后测试条件。我修改了你的代码:

#include <stdio.h>
char input[10];
char breakout = '!';
int idx;

int main(void)
{
    printf("Input characters until %c character is used to break out", breakout);

    for(idx = 0; idx < 10; idx++)
    {
            scanf("%c", &input[idx]);
            if(input[idx] == '!')
              break;
    }
    printf("Program terminated:");

    getchar();
    return 0;
}
于 2013-10-20T03:00:32.170 回答