Ali A
Ali A

Reputation: 53

How can I write words in a string reverse?

I am having a struggle with the following exercise in my book:

Write a program that prompts the user to enter a series of words separated by single spaces, then prints the words in reverse order. Read the input as a string, and then use strtok to break it into words.

Input:hi there you are cool
Output: None it shuts itself.
Expected:cool are you there hi

My program only gets the string and waits and shuts after a couple of seconds. Here's the code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void){
    int ch ;
    char * str , * str2;
    char * p;
    str = (char*)malloc(sizeof(char) * 100);
    str2 =(char*)malloc(sizeof(char) * 100);

    if((fgets(str , sizeof(str) , stdin)) != NULL){
        str = strtok(str ," \t");
        p = strrchr(str , '\0');
        strcat(str2,p);
        printf("%s",p);
       while(str != NULL){
          str = strtok(NULL ," \t");
          p = strrchr(str + 1, '\0');
          strcat(str2,p);
          printf("%s",p);
       }
    } 

    return 0;
}

I know this question has been asked here. I get the idea there but my problem is implementation and carrying out. This is more of a beginner question.

Upvotes: 0

Views: 153

Answers (1)

Ackdari
Ackdari

Reputation: 3498

Since you yourself stated that this is for an exercise I will not provide a working solution but an outline of what you might want to do.

Functions you want to use:

  • getline - for an easy read of an input line (notice that the newline character will not be eliminated
  • strtok_r to get the tokens (i.e. the words) from the input string
    • the _r means that this function is re-entrant which means that it can saftly be called by multiple threads at the same time. The normal version has an internal state and strtok_r lets you manage that state via a parameter.

(Please also read the docs for these functions if you have further questions)

For the algorithm: Use getline to read a single line from input and replace the newline character with the 0 char. Then you should extract all one token after the other from the input and store them in a stack like fashion. After you tokenized the input just pop the token from the stack an print them to the stdout.

Another approach would be:

Write a function that simply reverses a string. Then use this function to reverse the input string and then for all tokens to read the token from the reversed input string and print the reverse token to stdout.

Upvotes: 1

Related Questions