简体   繁体   中英

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

I am making a system where you register customers and write them on a file and read off of it but i'm stuck at registering where I need to ask for their name, ID and phone number, i want to print them out on a file on one line but when i print it out to check results it's automatically printing each string followed by a new line, how can i make it on one line separated by spaces so it can be easy for my to read from a file and get the info?

#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
}

This is happening because fgets() adds a trailing newline character. You can remove it by doing this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM