0

I have this code:

#include <stdio.h>

int create_logfile(char *name, char *field, char *joindate)
{
    FILE *ofile;
    ofile = fopen("test.txt", "a+");

    if(ofile == NULL)
        return 1;

    fprintf(ofile, "%s\t%s\t[%s]\n", name, field, joindate);

    fclose(ofile);

    return 0;
}

int main()
{
    char name[100], field[100], joindate[100];

    printf("Name: ");
    fgets(name, sizeof(name), stdin);
    printf("Field: ");
    fgets(field, sizeof(field), stdin);
    printf("Date: ");
    fgets(joindate, sizeof(joindate), stdin);

    create_logfile(name, field, joindate);
}

It gives this output:

John Doe
    Programmer
    [15/06/96
]

But is supose to give it like this:

John Doe    Programmer  [15/06/96]

What is worng and how do i fix it?

Edited by MasterHacker110

3
Contributors
3
Replies
20
Views
3 Years
Discussion Span
Last Post by MasterHacker110
0

fgets() includes the newline that terminated input for a successful call. If it's there you need to remove it:

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

char *fgets_trim(char *s, int n, FILE *in)
{
    char *p = fgets(s, n, in);

    if (p) {
        s[strcspn(s, "\n")] = '\0';
    }

    return p;
}

int main(void)
{
    char s[BUFSIZ];

    if (fgets_trim(s, sizeof s, stdin)) {
        printf("'%s'\n", s);
    }

    return 0;
}

However, note that the newline is important information. If it's not present after fgets() returns then that means you may have read a partial line. If you continue to push through with your normal logic then you may get garbage results. So take care in just automatically removing the newline without considering other error handling strategies.

A more thorough approach might be with a dynamically allocated string that grows to meet input needs:

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

char *dgets_trim(FILE *in)
{
    char *p = NULL, *temp;
    size_t size = 0, end = 0;
    char buf[BUFSIZ];

    while (fgets(buf, sizeof buf, in)) {
        size += strlen(buf);
        temp = (char*)realloc(p, size + 1);

        if (!temp) {
            break;
        }

        p = temp;
        strcpy(p + end, buf);
        end = size;

        if (p[end - 1] == '\n') {
            p[end - 1] = '\0';
            break;
        }
    }

    return p;
}

int main(void)
{
    char *s = dgets_trim(stdin);

    if (s) {
        printf("'%s'\n", s);
        free(s);
    }

    return 0;
}

But ultimately your problem is the trailing newline after each fgets() call. Remove that and your output will look like you want.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.