Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Assignment 5: Reverse Words In this assignment you must write a program that tak

ID: 3640631 • Letter: A

Question

Assignment 5: Reverse Words

In this assignment you must write a program that takes a string from stdin using fgets(), then

prints out the sequence of words in reverse. Below is a test run of the program, with the user

input underlined:

$ ./output

Note that the characters within the words are printed in the correct order, but the words

themselves are printed in reverse order. Here is a more detailed specification of the

requirements of your program:

1.

newline.

2.

fgets, its type information, and which library contains it.

good reference (make sure to read about the differences between gets() and fgets()). We

haven't yet covered this in class, but you should be able to understand the function's type and

usage from the slides, the book, and the Internet.

3.

(see below). You may assume that there will be at most 512 words, that all the words will be

separated by spaces (but not necessarily just a single space), and that the first character will

be a letter. Only a single space should separate each word in the output, even if the two

words were originally separated by more than one space in the input.

Hint

original input is stored in buffer, we can replace the first space character following each word

with a null character (''). Moreover, every time we encounter the first letter of a word, we set

a new pointer in out pointer array words to the address of that word. Note that multiple spaces

in the original buffer are condensed into a single space in the output.

yo u ca n cag e a swallo w ca n ’ t yo u

you can’t swallow a cage   can   you

                                     m a ry ( 2 space) l o v e s (1 space ) l a m b s (1 space)

(note the two spaces after “mary”)

                                      modified buffer

                  m a r y (1 space )l o v e s l a m b s (1space)

Output of your program with this input buffer:

lambs love mary

Explanation / Answer

#include #include #include int main() { char buffer[1024], words[512][100]; fgets(buffer,sizeof(buffer),stdin); if(buffer[strlen(buffer)-1]==' ') buffer[strlen(buffer)-1]=''; int k=0; char *p; p=strtok(buffer," "); while(p!=NULL) { strcpy(words[k++],p); p=strtok(NULL," "); } for(int i=k-1;i>=0;i--) printf("%s ",words[i]); return 0; }