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

标签 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*/

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

最佳答案

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

关于c - 出于某种原因,printf 函数在我要显示的内容上添加了一个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37190547/

相关文章:

c - 系统崩溃时 clflush 或 clflushopt 是原子的吗?

c - 将一个字符分配给一个字符串

C - exec 是否必须在多线程进程中立即跟随 fork?

C 程序打印范围

c++ - 将 Linux 兼容项目从 Windows 移植到 Linux

c - C 中不正确的插入队列

c - 在 C 中连接字符串的最谨慎的方法

c - 是否可以仅打印出 C 字符串的特定部分,而不制作单独的子字符串?

c - 在 C 中的多列中打印 ASCII 字符

c - C 中的 snprintf 问题