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