繁体   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