簡體   English   中英

為什么用換行符放置字符串? 我試圖讓它把這三個輸入作為一個字符串放在一行

[英]Why are the strings being placed with a newline? I'm trying to make it take those three inputs as a string on one line

我正在制作一個系統,您可以在其中注冊客戶並將他們寫在文件上並讀取它,但我被困在注冊的地方,我需要詢問他們的姓名、身份證和電話號碼,我想將它們打印在文件上在一行上,但是當我打印出來檢查結果時,它會自動打印每個字符串,然后是一個新行,我怎樣才能讓它在一行上用空格分隔,這樣我就可以很容易地從文件中讀取並獲取信息?

#include <stdio.h>
#define VARSIZE 80

int main(void) {
    char customerName[VARSIZE], ID[VARSIZE], phoneNumber[VARSIZE];

    puts("Input the following:");
    puts("First and last name");
    printf(">");
    scanf_s("[^\n]c", customerName, VARSIZE);
    fgets(customerName, VARSIZE, stdin);
    printf("Enter ID for %s", customerName);
    printf(">");
    scanf_s("[^\n]s", ID, VARSIZE);
    fgets(ID, VARSIZE, stdin);
    printf("Enter phone number for %s", customerName);
    printf(">");
    scanf_s("[^\n]s", phoneNumber, VARSIZE);
    fgets(phoneNumber, VARSIZE, stdin);
    puts("\nUser registered!\nYou will be placed back in the menu now.\n");
    
    // this is for file writing
    //fprintf(write_file, "%s%s%s", customerName, ID, phoneNumber);

    printf("%s %s %s", customerName, ID, phoneNumber); //just to see output
}

發生這種情況是因為fgets()添加了尾隨換行符。 您可以通過執行以下操作將其刪除:

customerName[strcspn(customerName, "\n")] = 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM