I'm having trouble reversing the letters of words in a sentence, for instance:
Input: This is a test
Output: sihT si a tset
However, when I run the program and have the same input as above, my output is just the first word reversed. Here is my code:
Code:#include<stdio.h> #include<string.h> void rev_str(char *string, size_t length) { int start, end; for (start = 0, end = length-1; start < end; start++, end--) { char swap = string[start]; string[start] = string[end]; string[end] = swap; } } char *rev_words(char *str) { int length; char *p = str, *next; for (p = str; p != 0; p = strpbrk(p, " ")) { if (*p == ' ') { p++; } next = strpbrk(p, " "); length = (next != 0) ? next - p : &str[strlen(str)] - p; rev_str(p, length); } return str; } int main(void) { char str[100]; printf("Enter your sentence:"); scanf("%s", str); printf("%s\n", rev_words(str)); return 0; }



LinkBack URL
About LinkBacks



