I have a problem which after many tests I think it's due to me not understanding how the input buffer works.
I have a while cycle which should continue to iterate until the user types "no" to stop the iteration.
I have two problems.
- The while never stops to iterate regardless the user enters "no" or whatever is not equal to "yes"
- As you can see the output at the second cycle has a problem. The program doesn't ask the user to input a string and skip that step, like the user just types ENTER.
CODE:
int foo = 0;
do{
int i, cycles;
char array[MAX_LENGTH+1];
for(cycles=0; cycles < MAX_READ_CYCLES; cycles++){
i=0;
printf("\n\nEnter a string: ");
char ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
array[i] = ch;
i++;
}
array[i] = '\0'; //string terminator
printf("String you entered: %s\n", array);
printf("\nDo you want to continue? 1: yes / 0: no \n");
scanf("%d", &foo);
}
} while( foo == 1);
OUTPUT
Enter a string: test
String you entered: test
Do you want to continue? 1: yes / 0: no
0
Enter a string: String you entered:
Do you want to continue? 1: yes / 0: no
3
Enter a string: String you entered:
Do you want to continue?