5

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.

  1. The while never stops to iterate regardless the user enters "no" or whatever is not equal to "yes"
  2. 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?
fbid
  • 1,570
  • 2
  • 18
  • 29

2 Answers2

5

Your program doesn't terminate if the user enters "yes" because of the inner 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 flush stdin and http://c-faq.com/stdio/stdinflush2.html

Community
  • 1
  • 1
orestisf
  • 1,396
  • 1
  • 15
  • 30
0

You are creating a character array of 3 bytes and then storing more than three bytes into it. Don't forget that there will be a null tacked onto the end of that. Since you are not allocating enough space you are overwriting other memory locations which will always create undefined behavior.

Note, also, that scanf here is very unsafe. It's also not valid to initialize a character array like this: char foo[3]="";

David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
  • You are right about the `foo[3]` array, it was just quick example to reproduce a simple test case. Anyways, even if I use an integer variable, `int foo = 0' and then replace the while condition to `while( foo == 1)' the problem persist. – fbid Dec 24 '15 at 17:41