-1

I'm new on programming and I have started learning C language by my own. Although there is an issue on the following screenshot that I am not able to understand its logic. Specifically I don't know why C skips the part of scanf in the called function. Does the order of calling matter? Thank you very much.

Here is the screenshot: https://i.stack.imgur.com/v7XTg.jpg

#include <stdio.h>
void GiveLetter(); // function prototype #1
void GiveNumber(); // function prototype #2
int main ()
{
    int x;
    printf("Give me the first number:");
    scanf("%d",&x);
    printf("Your first number is: %d\n",x);
    printf("Hello Panos\n");
    GiveLetter();
    GiveNumber();
    return 0;

}
void  GiveLetter()
{
    char Letter;
    printf("Give a letter:\n");
    scanf("%c",&Letter);
    printf("Your letter is %c\n",Letter);
}
void GiveNumber()
{
    int Number;

    printf("Give the second number:");
    scanf("%d",&Number);
    printf("Your second number is %d\n",Number);
}

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Navy Alsk
  • 27
  • 8

1 Answers1

3

You scanf a number in main(). That leaves the ENTER in the input buffer which is read by the scanf inside the function.

Ask scanf to ignore whitespace (unlike "%c", "%d" already ignores whitespace on its own)

scanf(" %c", ...);
//     ^ ignore whitespace

Better yet. Use only fgets() for user input. It's a safe alternative, with good error reporting and recovery.

pmg
  • 106,608
  • 13
  • 126
  • 198
  • The problem appears when i call the function "GiveLetter".I tried to call it before the variable definition in the main and it worked.i dont know why. – Navy Alsk Jun 16 '19 at 15:47
  • @NavyAlsk, It worked because the input buffer is empty when you call the function before the ```int x```, If you call the function ```GiveLetter()``` after ```scanf("%d",&x);``` statement, then input buffer contains the ```ENTER``` character, so in the next scanf statement the ```ENTER``` character is read as next input, and it seems to the user as if the ```scanf()``` has been skipped by the program, to avoid this case follow the above answer by @pmg – Saurabh P Bhandari Jun 16 '19 at 16:06
  • Thank you very much to both of you.You have helped me so much.I apologize for asking too much but as i said i have just started learning ! :) – Navy Alsk Jun 16 '19 at 16:23