Home > Back-end >  Why are the strings being placed with a newline? I'm trying to make it take those three inputs
Why are the strings being placed with a newline? I'm trying to make it take those three inputs

Time:12-02

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
}

CodePudding user response:

This is happening because fgets() doesn't remove the trailing newline character. You can remove it by doing this:

customerName[strcspn(customerName, "\n")] = 0;
  •  Tags:  
  • c
  • Related