2016-05-12 37 views
2

我試圖在列中顯示文本,但在輸出的第二行添加了空格。我做錯了什麼? (該條目不包含字符串前空格)以下是所涉及的功能:如上所示出於某種原因,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*/ 

任何輸入數據將被打印。

+2

這個問題似乎並沒有在這裏。請使用[最小,完整,可驗證示例](http://stackoverflow.com/help/mcve)更新您的問題。 – dbush

回答

9

您應該將\n替換爲格式字符串而不是字段。由於Mobile number有13個字符,加上\n 14,並且爲%-15s添加了一個空格作爲填充,因此它在下一行中位於\n之後。

相關問題