0

I am trying to figure out the best way to get an integer and a character from a user

Here is what I have so far:

#include <stdio.h>
int main()
{
    int a;
    char b;
    printf("enter the first number: \n");
    scanf("%d", &a);
    printf("enter the second char: \n");
    scanf("%c", &b);

    printf("Number %d",a);
    printf("Char %c",b);
    return 0;
}

The output is not shown correctly. Is there any problem with this? enter image description here

hellow
  • 12,430
  • 7
  • 56
  • 79

3 Answers3

3

Your input and output statements are fine. Just replace printf("Number %d",a); with printf("Number %d\n",a); to better format the output. Also you should change your second scanf statement to scanf(" %c", &b);. This will deal with the newline character entered after the number is inputted.

Mayank Kumar
  • 1,133
  • 3
  • 13
  • 20
2

After you enter the number, you pressed the Enter key. Since the scanf function works on the input stream, when you try to process the next char after reading the number, you are not reading the character you typed, but the '\n' character preceding that. (i.e. because the Enter key you pressed added a '\n' character to your input stream, before you typed your char)

You should change your second call to scanf with the following.

scanf(" %c", &b);

Notice the added space character in the formatting string. That initial space in the formatting string helps skip any whitespace in between.

Additionally, you may want to add \n at the end of the formatting strings of both printf calls you make, to have a better output formatting.

ilim
  • 4,477
  • 7
  • 27
  • 46
0

Here you need to take care of hidden character '\n' , by providing the space before the %c in scanf() function , so the "STDIN" buffer will get cleared and scanf will wait for new character in "STDIN" buffer .

modify this statement in your program : scanf("%c",&b); to scanf(" %c",&b);

new_learner
  • 131
  • 10