1

I managed to make this simple two part program which consists of simple print and scan functions. The first part is an addition operation and the second part asks the user for a letter and then it repeats it to the user. The first part goes well but when it finishes and is supposed to start the second part it shows the whole thing before I can input a letter.

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>

int main()
{
int num1, num2 = 522;/*input a number*/ /*add 522*/
int sum; /*sum of num1 and num2*/
char let;   /*Letter to put in*/

printf("Hello, my name is John Doe.\n"); /*Print "Hello my name is*/
printf("Please type a number= "); /*Ask user for num1*/
scanf("%d", &num1);   /*Scan for num1*/
sum = num1 + 522;   /*Add 522 to num1*/
printf("The sum of %d and %d is %d\n", num1, num2, sum);/*print num1 and sum*/
printf("Please type a letter= \n");   /*Ask user for letter*/
scanf("%c", &let);   /*Scan for letter*/
printf("You typed %c\n", let);    /*Show the letter input*/
return 0;

}
oporock
  • 21
  • 2
  • 1
    Please go easy on the comments, they just re-state what is pretty clear from the code. `/* Remind OP to go easy on the comments. */` – M Oehm Jan 27 '16 at 06:32

2 Answers2

7

Change

scanf("%c", &let);

to

scanf(" %c", &let); 

There is a newline character after a number is entered so that is picked by %c you need to ignore it. Note the space before %c

Gopi
  • 19,784
  • 4
  • 24
  • 36
0

A better approach is flushing the input buffer after every scanf()/getchar() call.

while ((ch = getchar()) != '\n' && ch != EOF);

but don't use fflush(stdin) because if the file stream is for input use, as stdin is, the behaviour is undefined, therefore it is not acceptable to use fflush() for clearing keyboard input. As usual, there are some exceptions, check your compiler's documentation to see if it has a (non-portable) method for flushing input.

you can use getchar() function as well to clean the new line character but first method is recommended.