简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM