C - solution-based user method do / while not working correctly

I have a problem which, after many tests, I think because of this I don’t understand how the input buffer works.

I have a while loop that should continue to iterate until the user types β€œno” to stop the iteration.

I have two problems.

  • It never stops at the iteration, regardless of the fact that the user enters "no" or something else is not "yes"
  • As you can see, the output in the second loop has a problem. The program does not ask the user for a line input and skips this step, for example, the user simply enters 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? 
+5
source share
2 answers

Your program does not end if the user enters "yes" due to an internal for loop:

 #include <stdio.h> #include <string.h> #define MAX_LENGTH 100 #define MAX_READ_CYCLES 100 int main() { int cycles = 0; char foo[4]; do { char array[MAX_LENGTH + 1]; printf("\n\nEnter a string: "); char ch; int i = 0; 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?"); scanf("%s", foo); cycles++; while ((ch = getchar()) != '\n' && ch != EOF); // force drop stdin } while (strcmp(foo, "yes") == 0 && cycles < MAX_READ_CYCLES); } 

Also see I am not able to clear STDIN and http://c-faq.com/stdio/stdinflush2.html

+5
source

You create an array of characters from 3 bytes, and then store more than three bytes in it. Do not forget that at the end of this will be zero. Since you are not allocating enough space, you are overwriting other memory cells that will always create undefined behavior.

Please note that scanf is very unsafe here. It is also not valid for initializing a character array as follows: char foo[3]="";

0
source

Source: https://habr.com/ru/post/1239152/


All Articles