0

I am working on a program for my comp sci classes and the problem asks to take a command from the user and the string that. Then, use either "reverse " to reverse the string that follows or "create " to print the string that follows. The reverse output should keep the words reverse, then print the string that follows in reverse.

/* for Reverse command */
else if(strcmp(str,"reverse ") > 0)
{
    reverse(str);
    printf("Reverse of string: %s\n", str);
}

The following function is used to reverse the word:

void reverse(char *string)
{
    int length, i;
    char *begin, *end, temp;

    length = strlen(string);

    begin = string;
    end = string;

    for (i = 0 ; i < (length - 1) ; i++)
    end++;

    for (i = 0 ; i < length/2 ; i++)
    {
       temp = *end;
       *end = *begin;
       *begin = temp;

     begin++;
     end--;
    }
}

The output reverses all the words and prints. Is there a way to break off the reverse part of the string before it is passed to the reverse function?

8
  • Show some output of the code, and what you want to output. Commented Nov 21, 2014 at 15:16
  • Give a command: reverse hello world Reverse of string: dlrow olleh esrever Commented Nov 21, 2014 at 15:17
  • That's what's actually happening or what you expect? Please edit in your question. Commented Nov 21, 2014 at 15:19
  • I want the output to be "reverse dlrow olleh" Commented Nov 21, 2014 at 15:19
  • Then all you have to do is to read 2 strings instead of 1.The first string will be the command(you don't reverse it), and the second string you will apply the reverse(). All this is assuming you read reverse hello world in one string. Commented Nov 21, 2014 at 15:21

1 Answer 1

1

Before calling the function reverse, use

char *ptr=strchr(str,' ');
str=++ptr;

To cut off "reverse" from str.string.h needs to be included to use strchr.strchr returns a pointer to the first occurrence of the character ' ' in the string str, or NULL if the character is not found.ptr is incremented once before assigning it to str to remove the space from the string.

Sign up to request clarification or add additional context in comments.

3 Comments

I get this error "incompatible types when assigning to type ‘char[200]’ from type ‘char *’"
My str variable is defined as str[200]
@nerd4life ,Try strcpy(str,++ptr); instead of str=++ptr;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.