Start New Discussion within our Software Development Community

Hello! I have an output problem with a program that I'm writing that takes a user inputed sentence and reverses the words within it. Right now the program compiles and runs without problem, but my output is different than what is intended. specifically, there is an extra newline placed after the first word

For example

Output SHOULD be:
./reverse
Enter text: The car raced down the lane
lane the down raced car The

Instead I'm getting:
./reverse
Enter text: The car raced down the lane
lane
[space]the down raced car The

Can someone help me get rid of the extra newline?

#include <stdio.h>

#define MAX_CHAR 80

void reverse(char *sentence);

int main()
{
   char sentence[MAX_CHAR];

   printf("Enter text (words, up to 80 characters): ");
   fgets(sentence,MAX_CHAR + 1,stdin);

   reverse(sentence);
   printf("\n");
   return 0;

}


void reverse(char *sentence)
{
   char reversed[MAX_CHAR + 1];
   char *end = reversed;
   int char_num = 0;

   while(sentence[char_num] != '\0')
     char_num++;

   while(*sentence == ' ')
      ++sentence;

   if ( *sentence == '\0')
      return ;


   else
   {
      while (*sentence != '\0' && *sentence != ' ')
      *end++ = *sentence++;
   }

   *end = '\0';

   reverse(sentence);

   printf("%s ", reversed);

}

fgets() read the <Enter> key into the buffer if the buffer is large enough to hold it. It's done that way by design so that the program can tell whether all the line was read or not. If the '\n' exists at the end of the line then the entire line was read. If '\n' does not exist at the end of the line then that means the buffer was not large enough to hold all the line and fgets() should be called again to finish reading the line.

What your program is missing is to remove the '\n' from the buffer. One way to do that on line 13 is like this:

char* ptr;
if( (ptr = strrchr(sentense,'\n')) != NULL)
   *ptr = '\0';
This article has been dead for over six months. Start a new discussion instead.