Reputation: 99
I am trying to write a simple demonstration program that will break out of a loop upon entering a designated character. I was able to do this successfully until I wanted to add the extra condition that I did not exceed my array. This code will not break out of the loop when I enter the designated character and I cannot figure out why. The logic and setup of the code seems sound!
#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;
}
It seems as though the condition of the for loop SHOULD evaluate false upon entering the '!' character, but it is not. Thanks guys
Upvotes: 0
Views: 1449
Reputation: 97672
You are testing the condition before the character is entered, if you use a do-while loop you can make the comparison after
idx = 0;
do
{
scanf("%c\n", &input[idx]);
}
while( input[idx++] != breakout && idx < 10);
Upvotes: 2
Reputation: 69
You should testing the condition after the character is inputted. I modified your code:
#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;
}
Upvotes: 1
Reputation: 2750
Think about your for loop conditions. Your input[idx]
is always looking at the next location in the array (which does not yet contain a character)--not the previous character received from the scanf call, which would be found at input[idx - 1]
. But of course you can't check input[idx - 1]
on the first iteration, so watch out for that.
for(idx = 0; (idx == 0 || input[idx - 1] != breakout) && idx < 10; idx++)
{
...
}
Super-complex for loop conditions are rarely a good idea for more or less this reason--that idx++
iteration step occurs before the evaluation of the condition and it can be confusing. Use a do/while or have a break condition in your loop.
Upvotes: 2