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);
}