1

So for a class I am taking I have to learn C and one program I am trying to make is a simple print face program that takes 3 inputted characters and uses them to create a face.

However, whenever I run it, it asks for the eye character, then prints out the "Enter nose character: " but never takes any input, instead skipping right to the mouth character. I have looked over the code and cannot figure out what is causing this.

#include <stdio.h>

void PrintFace(char eye, char nose, char mouth) {

   printf("\n  %c   %c\n", eye, eye); // Eyes
   printf("    %c\n", nose);        // Nose
   printf("  %c%c%c%c%c\n",
          mouth, mouth, mouth, mouth, mouth); // Mouth

   return;
}

int main() {
   char eyeInput;
   char noseInput;
   char mouthInput;

   // Get character for eyes
   printf("Enter eye character: ");
   scanf("%c", &eyeInput);

   // Get character for nose
   printf("Enter nose character: ");
   scanf("%c", &noseInput);

   // Get character for mouth
   printf("Enter mouth character: ");
   scanf("%c", &mouthInput);

   // Print the face using the entered characters
   PrintFace(eyeInput, noseInput, mouthInput);

   return 0;
}

This is the output I get:

Enter eye character: o
Enter nose character: Enter mouth character: l

  o   o


  lllll

It seems to skip the second scan statement but I can't see why. :/

Qwurticus
  • 877
  • 1
  • 10
  • 18

3 Answers3

2

Because the input stream is line-buffered, you need to press Enter after typing in the character. Now scanf reads a single character from the stream. However, there's still a newline in the stream, and that gets picked up on the next read.

One approach is to use fgets and read a whole line of text, then pick out the first character. However, doing this properly might be a little over the top.

It might be easier if you just use code to ignore characters up until the newline, as suggested here: C code for ignoring the enter key after input. Also, you should consider using getchar or getc instead of scanf. Just make a simple function to do all this stuff, and call it whenever you want to read a character.

Community
  • 1
  • 1
paddy
  • 60,864
  • 6
  • 61
  • 103
1

The carriage return you're passing by hitting "Enter" after your first character is considered a second character input. Notice the difference in carriage returns in your output.

See the linked question at: C: function skips user input in code

Community
  • 1
  • 1
renz
  • 11
  • 1
0

If I remember well, scanf does not take '\n' in a string. So you put for example "dog" as a first entry but you type an enter at the end. So the second scanf take that '\n' in the buffer shiting your program. Solution? Clean up your buffer. If you are over windows fflush() can save you, using fflush(stdin) after each scanf. Over unix fflush() does not work like that and you have to do it manually. An easy way is to put a getc() or something like that that consumes that '\n'

Abend
  • 589
  • 4
  • 14