2

I have a simple program which receives input from 3 different functions, 2 return ints, 1 returns a char, but the third function doesn't scanf for some reason it skips that step entirely.

#include <stdio.h>

int get_height();
int get_length();
char get_symbol();
void draw_rectangle(int h, int l, char s);

int main () {

    int h, l;
    char s;

    h = get_height();
    l = get_length();
    s = get_symbol();

    draw_rectangle(h, l, s);

    return 0;
}

int get_height() {

    int i;

    printf ("Please enter the height of the rectangle: ");
    scanf ("%d", &i);

    return i;
}

int get_length() {

    int i;

    printf ("Please enter the length of the rectangle: ");
    scanf ("%d", &i);

    return i;
}

char get_symbol() {

    char i;

    printf ("Please enter the symbol for the rectangle: ");
    scanf ("%c", &i);

    return i;
}

void draw_rectangle(int h, int l, char s) {
    printf ("%d %d %c", h, l, s);
}

When I run this, i can scan for height and length but it prints the prompt to scan for the char but then skips the user input and prints the value for h and l but no s. What am i missing here?

James M
  • 18,506
  • 3
  • 48
  • 56
user1895783
  • 381
  • 1
  • 3
  • 8

3 Answers3

3

Previous scanf leaves a newline in the input buffer which is consumed by:

scanf ("%c", &i);

Just change it to:

scanf (" %c", &i);

Notice the space. This will tell scanf to ignore all whitespaces.

P.P
  • 117,907
  • 20
  • 175
  • 238
2

You need to consume the newline characters that are being left by the previous scanf() calls. A simple way would be:

scanf ("%d", &i);
getchar();

in each function where it's used. Or with just the one call:

scanf(" %c", &i); 

the space will tell it to skip the previous tabs, newlines, or spaces.

stdin is buffered and when the user enters a digit you get a newline char too. The scanf taking the character is therefore picking up one of those left over newlines

Mike
  • 47,263
  • 29
  • 113
  • 177
  • Wouldn't the pattern "%d\n" accomplish the same thing without requiring a second function call? – Peter Gluck Dec 11 '12 at 19:58
  • @PeterGluck - Not exactly. That's going to cause the newline to be skipped as input but the scanf will keep waiting (you hit `` and it still waits for input), it will work oddly from the users perspective. The getchar() will consume the newline from the stream. The other 1 function option is to put a space before the `%c` which will tell scanf to ignore the previous newlines, tabs, and spaces – Mike Dec 11 '12 at 20:04
0

You can also use

fflush(stdin);
scanf("%c",&i);

It will resolve your problem. As fflush clears the buffer before reading the character

sushant goel
  • 821
  • 6
  • 8