fgets() includes new line in string

折月煮酒 提交于 2019-12-02 13:27:19

Try this.

int main()
{
    FILE *f;
    f = ("words", "r");
    char string[100];
    while (fgets(string, 100, f))
    {
        char * message = strtok(string, "\n");
        printf("%s", message);
    }
}

strtok tokenizes the string into your message, \n. fgets will capture the \n token

By design fgets reads a line (terminated with a \n) and keeps the \n in the line - provided the buffer was big enough. Just look if last character is a \n, and it is it replace it with a \0, actually reducing the len of line by one:

int main(void)
{
    FILE *f;
    f = ("words", "r");
    char string[100];
    while (fgets(string, 100, f))
    {
         if ((string[0] != '\0') && (string[strlen(string) -1] == `\n')) {
             string[strlen(string) -1] = `\0';
         }
         printf("%s", string);
    }
}

You cannot prevent fgets() from storing the '\n' at the end of the array supplied to it. If the array is too short, fgets() will not store the newline, it will leave the characters that do not fit in the array in the input stream to be read by the next input operation.

There are multiple ways to remove the trailing newline, which may or may not be present:

Using strcspn():

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

int main(void) {
    char string[100];
    FILE *f = fopen("words", "r");
    if (f != NULL) {
        while (fgets(string, sizeof string, f)) {
            string[strcspn(string, "\n")] = '\0';
            printf("%s", string);
        }
    }
    return 0;
}

Using strlen():

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

int main(void) {
    char string[100];
    FILE *f = fopen("words", "r");
    if (f != NULL) {
        while (fgets(string, sizeof string, f)) {
            size_t len = strlen(string);
            if (len > 0 && string[len - 1] == '\n')
                string[--len] = '\0';
            printf("%s", string);
        }
    }
    return 0;
}

Using strchr():

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

int main(void) {
    char string[100];
    FILE *f = fopen("words", "r");
    if (f != NULL) {
        while (fgets(string, sizeof string, f)) {
            char *p = strchr(string, "\n");
            if (p != NULL)
                *p = '\0';
            printf("%s", string);
        }
    }
    return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!