1

I'm trying to write a program that takes an entered string and reverses the order of words. It also counts how many words are in a statement. So if "batman and robin" was entered, it would print:

robin and batman
words in statement: 3

my program mostly works, but it prints in a strange way. This would be the output for "batman and robin" in the program I've written:

robin

and batman

words in statement: 2

I don't know why there's an extra newline that separates the first word from the rest. No matter what I input, the first word is always separated from the rest and the count is one off. I'm not sure where the extra newline is coming from. I could fix the count problem by just adding one to the count before I print, but I'm trying to find a better solution.

My code:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include<string.h>

int main(void) {
char ent[50], rev[50];
int length, i = 0, start, end, j = 0, count = 0, k;

printf("Enter a statement: ");
fgets(ent, 50, stdin);
//printf("%s\n", ent);

length = strlen(ent);
start = length - 1;
end = length - 1;


while (start > 0) {
    if (ent[start] == ' ') {
        i = start + 1;
        count++; 

        while (i <= end) {
            rev[j] = ent[i];
            i++;
            j++;
        }
        rev[j++] = ' ';
        end = start - 1;
    }
    start--;
}

for (i = 0; i <= end; i++) {
    rev[j] = ent[i];
    j++;
}

rev[j] = '\0';
//count = count + 1;

printf("Reversed statement: %s\n", rev);
printf("Words in statement: %d\n", count);

return(0);
}
  • 1
    Side note: Instead of writing `fgets(ent, 50, stdin);`, you can write `fgets(ent, sizeof ent, stdin);`. This has the advantage that if you ever change the size of `ent`, then you will only have to change one number, not two. If you don't do this, then you risk having a bug if you change the number in one place, but forget to change it in the other place, too. – Andreas Wenzel Oct 23 '21 at 21:44

1 Answers1

0

If the function fgets reads a newline character, then it will also write it into the string.

Due to this, the first word that you will write to rev is not "robin", but rather "robin\n". That is what is causing the undesired output that you posted.

You can either deal with the newline character, or simply remove it immediately after calling fgets. See this question on what the best ways are to remove the newline character:

Removing trailing newline character from fgets() input

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39