出于某种原因,printf函数为我想要显示的内容添加了一个空格

时间:2016-05-12 14:53:23

标签: c printf

我正在尝试在列中显示文本,但在输出的第二行添加了一个空格。我做错了吗? (条目在字符串之前不包含空格)以下是涉及的函数:

add(List *book)
{
    Contact *runner = book->una;
    Contact *node = (Contact *) malloc(sizeof(Contact));

if (node == NULL);
else {
    printf("Add a contact\n");
    printf("Enter the first name: ");
    scanf("%s", node->fname);
    printf("Enter the last name: ");
    scanf("%s", node->lname);
    printf("Enter the mobile number: ");
    scanf("%s", node->number);
    printf("\nContact added!\n\n");
    node -> next = NULL;
    if(book->una == NULL){
        book->una = node;
    }
    else
    {
        while( runner->next != NULL)
        {
            runner = runner->next;
        }
        runner->next = node;
    }
}
}

    display(List *book)
{
    Contact *runner = book -> una;
    if(runner == NULL)
    {
        printf("%20s", "PHONEBOOK EMPTY!");
        return;
    }
    printf("Contact list\n");
    printf("%-15s%-15s%-15s", "First Name", "Last Name", "Mobile number\n");
    while( runner != NULL)
    {
        printf("%-15s%-15s%-15s\n", runner->fname, runner->lname, runner->number);
        runner = runner->next;
    }
}

/*An example output basically turns out like this:

First Name         Last Name         Mobile Number
 James              Harrison          123456
Wendy              Barnes            00000
Cam                Rodriguez         575938*/

将打印任何输入数据,如上所示。

1 个答案:

答案 0 :(得分:9)

您应该将\n放在格式字符串中而不是字段中。由于Mobile number有13个字符,加上\n 14,并且一个空格被添加为%-15s的填充,因此它会在\n之后,在下一行中。< / p>