John
John

Reputation: 115

While GetChar != EOF terminating inconsistently

I have these two blocks of code, the aim of both of which is to get some user inputs, to make a cryptography script.

int keyPrompt(){
  /* this prompts the user for the Caesar encryption key */
  int c;
  printf("Enter key value between 1-9: ");
  while((c=getchar()) != EOF && c != '\n'){
    return c;
  }
}

int cryptPrompt(){
  /* this asks the user whether they want to encrypt or decrypt */
  int d;
  printf("Do you want to encrypt or decrypt?(E/D): ");
  while((d=getchar()) != EOF && d != '\n'){
    /*
    if(d == 'E'){
      return 1;
    }
    else if (d == 'D' ){
      return -1;
    }
    */
    return d;
  }
}

The problem I'm having is that when I run the file, the first while loop behaves as I expect it to: I enter a value, hit enter and it goes to the next line. With the second while loop, when it executes the function, it skips asking the user for an input and simply goes straight to the next line of good, not storing any return value.

Any idea why it's doing this?

Upvotes: 0

Views: 62

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126175

Consider what this code does:

int keyPrompt(){
  /* this prompts the user for the Caesar encryption key */
  int c;
  printf("Enter key value between 1-9: ");
  while((c=getchar()) != EOF && c != '\n'){
    return c;
  }
}

After printing the prompt, it reads an input character. If that character is an EOF or a newline, it exits the loop and falls off the end of the function (without a return, which leads to undefined behavior if the returned value is not ignored). If its NOT an EOF or newline, it returns the character.

In no case will the while loop ever actually loop.

Consider what happens if you call this code and enter a key+newline. The key will be read and returned, and the newline will be left in the input buffer. Now consider what happens if you call another function like this -- the first thing it will read is the newline left over from the keyPrompt function...

Upvotes: 3

Related Questions