0

I tried to do something simple to write some detail that I got from user to a txt file and it works but I want them to be at the same line and for some reason the last one that I write is in the next line.

printf("\nPassengers Details:\n===================\n");

printf("Please Enter Passenger`s Passport-->:");
scanf("%d", &p1.passportnum);
getchar();
printf("\nPlease Enter Passenger`s First NAME-->:");
fgets(p1.firstname, SIZE, stdin);
printf("\nPlease Enter Passenger`s Last NAME-->:");
fgets(p1.lastname, SIZE, stdin);

fpassengers = fopen("passengers.txt", "w");
fprintf(fpassengers,"%d %s %s", p1.passportnum, p1.firstname, p1.lastname);

fclose(fpassengers);

In the file it writes the first 2 at the same line and the last name in the next line .

How do I make them be at same line??

Donald Duck
  • 8,409
  • 22
  • 75
  • 99

1 Answers1

1

You have just to replace \n with \0in the last position of p1.firstname and p1.lastname. Here is a generic example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 128

int main() {
    FILE* fpassengers;
    int passport_num;
    char first_name[SIZE];
    char last_name[SIZE];

    printf("\nPassengers Details:\n===================\n");
    printf("Please Enter Passenger`s Passport-->:");

    scanf("%d", &passport_num);
    getchar();

    printf("\nPlease Enter Passenger`s First NAME-->:");
    fgets(first_name, SIZE, stdin);
    first_name[strlen(first_name)-1] = '\0';

    printf("\nPlease Enter Passenger`s Last NAME-->:");
    fgets(last_name, SIZE, stdin);
    last_name[strlen(last_name)-1] = '\0';

    fpassengers = fopen("passengers.txt", "w");
    if (fpassengers == NULL) {
        perror("Fopen");
        exit(EXIT_FAILURE);
    }
    fprintf(fpassengers,"%d %s %s", passport_num, first_name, last_name);

    fclose(fpassengers);
}

You have also to check the return value of fopen.

Overflow 404
  • 482
  • 5
  • 20
  • You need to change: `last_name[strlen(first_name)-1] = '\0';` --> `last_name[strlen(last_name)-1] = '\0';`. That said, there are [better ways to remove the newline](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input). Note that the method you use has UB if the input string is empty or if there is an error in `fgets()`. Also, better and less error-prone to use `fgets()` and `sscanf()` instead of combining `scanf()`, `getchar()` and `fgets()`. – ad absurdum May 31 '17 at 16:20
  • And, `int main()` is an implementation-dependent signature; should be `int main(void)` or `int main(int argc, char **argv)` – ad absurdum May 31 '17 at 16:20