-2

I get the words from my document extracted and all are printed on screen, but after each word printed there is a blank line. How can I avoid reading or adding this new line to the string?

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

This code was not copy pasted, so I could have forgotten tiny pieces but should work. In words.txt I have one word on each line. My program prints them all to screen, but adds a new line after each word. I do not want it to add a new line, or a space. So if the txt had Hello on one line and Bye on the next line, I want it to print HelloBye. The objective of the final program will not be to print the string, it will be to use the string for something else, so I do need a string that only has the text without spaces at the end or new lines.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
liquidzorch
  • 31
  • 1
  • 1
  • 5

3 Answers3

1

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);
    }
}
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • 1
    The conditional code is complex compared with `string[strcspn(string, "\n")] = '\0';` — and inefficient if the compiler doesn't recognize that `strlen()` need only be called once as long as the result is saved. The code using `strcspn()` works correctly even if the string is empty or contains no newline. – Jonathan Leffler Sep 08 '18 at 10:01
0

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
-1

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

d0nut
  • 2,835
  • 1
  • 18
  • 23
  • This work for my application. Getting correct results now. Thank you. – liquidzorch Aug 08 '15 at 17:46
  • @liquidzorch no problem. – d0nut Aug 08 '15 at 17:46
  • 1
    strtok is overkill here. – Serge Ballesta Aug 08 '15 at 18:14
  • @SergeBallesta feel free to post your answer, then – d0nut Aug 08 '15 at 18:15
  • Done. Anyway your solution is perfectly right and fully answers the question. Just thinking that looking if last character of a string is `\n` and replacing it with `\0` is somewhat simpler. – Serge Ballesta Aug 08 '15 at 18:21
  • @SergeBallesta I'm happy for you – d0nut Aug 08 '15 at 18:22
  • 1
    Be aware that while `strtok()` is OK in a main function like this, it is not usually OK in a library function because `strtok()` is — poisonous. If a function that is using `strtok()` to parse a string calls another function that in turn uses `strtok()`, the calls in the other function wreck the behaviour of the sequence of calls in the calling function. Similarly, the library function cannot call any function that in turn uses `strtok()` because its use of `strtok()` will be wrecked. On Unix (POSIX) systems, use `strtok_r()`; on Windows, use `strtok_s()`. These don't wreck things. – Jonathan Leffler Sep 08 '18 at 10:12