Search code examples
cscanfnewlineenterhit

scanf without newline (C programming)


I dont want to newline after scanf.

printf("I am  ");
    scanf("%d", &age);
    printf(" years old");   

This output is;

 I am 19
years old.

But i want to like this:

I am 19 years old.

Solution

  • You're not using scanf() properly. The function scanf() takes in user input and then stores it in a variable, and in your case that would be the variable 'age'. After that you can place the variable age in the printf() statement like this.

    scanf("%d", &age);
    printf("I am %d years old.", age);
    

    That code will first wait for the user to enter an age then it would print the sentence:

    I am X years old.

    The reason your screen is displaying your output on two lines is because the, "scanf("%d", &age);" requires you to hit enter after you type in a number (which creates a new line) in order for "printf(" years old");" to execute. Also, when you are hitting enter in your code, the number being stored in the variable 'age' isn't doing anything. You're just storing it for no reason.