cHam
cHam

Reputation: 2664

Stuck with C file i/o

I have a C program that reads from a txt file. The text file contains a list of words, one word per line. What I want to do is get the words from the text file and print them as one sentence/paragraph, however, when I try to print them, they still print one word per line. I am storing the words in a 2d char array as I read them from the file. What I think is happening is the array copies the newline char from the txt file, is that correct? and if so, how do I add the word into the array without the new line char?

    while(fgets(line,20,lineRead)!=NULL)
    {
        for(j = 0; j < 20;j++)
        {            
            message[k][j]= line[j];

        }
        printf("%s", message[k]);
    }

I tried a few while loops with no success:

while(line[j] != ' ')        
while(line[j] != NULL)       
while(line[j] != EOF)      
while(line[j] != ' \')

I'm learning C so please be specific in my error. I want to understand what I'm doing wrong, not just get an answer.

Thank you!

Upvotes: 0

Views: 240

Answers (4)

Sergey L.
Sergey L.

Reputation: 22562

The newline characters are part of the string, you need to remove them:

#include <string.h>

while(fgets(line,20,lineRead)!=NULL)
{
    char* newline_pos = strpbrk (line, "\n\r"); // get first occurance of newline or carriage return
    if (newline_pos) 
         *newline_pos = '\0';

    printf("%s ", line);
}

Upvotes: 1

Sidharth Mudgal
Sidharth Mudgal

Reputation: 4264

You should do:

while(fgets(line,20,lineRead)!=NULL)
    {        
        strcpy(message[k], line);
        if(message[k][strlen(line)-1] == '\n')
            message[k][strlen(line)-1] = '\0']
        printf("%s", message[k]);
    }

What this does is that it copies line into message[k] and then removes the last character if it is a newline character. We are checking the last character because the documentation says "A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str." So if newline is present it will be the last character.

Upvotes: 0

CrazyCasta
CrazyCasta

Reputation: 28362

You could simply change your for loop to be:

for(j = 0; j < 20 && line[j] != '\n';j++)
{            
    message[k][j]= line[j];
}
if(j < 20)
    message[k][j] = '\0';

Upvotes: 1

Hernan Velasquez
Hernan Velasquez

Reputation: 2820

The fgets functions includes the newline character \n in the buffer you are reading. Just include a conditional statement within your loop to copy all the characters except \n and \r. Something like:

if ( line[j] != '\n' && line[j] != '\r' ) {
    /* Copy the character in your new buffer */
}

Upvotes: 1

Related Questions