Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does scanf take two inputs when running this code?

When using the scanf function to take an input, two inputs are given.

For starters, I am a python programmer trying to learn C. I tried to search why this was happening but found nothing. Here is the code:

#include <stdio.h>

int main() {

    int age;

    printf("Enter your age: ");
    scanf("%d\n", &age);
    printf("Your age is %d\n", age);
    
    return 0;
}

When running and debugging in VSCode, this is what I get:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Enter your age: 23
12
Your age is 23

Any help would be appreciated.

>Solution :

The \n is unnecessary in the scanf format string. It tells scanf to continue reading any number of whitespace characters, until it finds the next non-whitespace character.

Instead, just use scanf("%d", &age);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading