Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printf inserts % at the end of the line

Tags:

c

printf

I'm writing a basic program to learn how to use basic input/output in C, and it works just fine. The only problem I have is when it prints, there is a "%" at the end of the string on the terminal. Here's my code:

#include <stdio.h>

int main(int argc, char **argv) {

    char name[32];

    printf("Enter your name: ");
    scanf("%s", name);

    printf("Hello, %s", name);

    return 0;

}

When I run the program, the output is Hello, Andrew%

Any help?

like image 705
ahalverson Avatar asked Apr 02 '14 15:04

ahalverson


People also ask

How do you end a printf line?

The entire line, including the printf function (the “f” stands for “formatted”), its argument within the parentheses and the semicolon (;), is called a statement. Every statement must end with a semicolon (also known as the statement terminator).

Does Scanf append new line?

scanf is only used to input values, now what you need is the your output to be on a new line, basically you want a newline to be printed on your screen, so you must use the \n in the printf as you want a new line to be printed.As for why it is asking for four inputs , Im not sure, the syntax says that you must you use ...

How do you add a new line in C?

The newline character ( \n ) is called an escape sequence, and it forces the cursor to change its position to the beginning of the next line on the screen. This results in a new line.


1 Answers

There's nothing in your code that should explain this behavior. However, it seems likely that if you are running this from a shell, that may be your shell prompt.

Add a newline to your output:

printf("Hello, %s\n", name);

This should cause the prompt to print on the next line as you probably expected.

like image 171
FatalError Avatar answered Sep 17 '22 22:09

FatalError