Help! I need to reverse a string!!

This is a discussion on Help! I need to reverse a string!! within the C++ Programming forums, part of the General Programming Boards category; Sorry for the lack of comments, but it's not too complicated. I need to make a function that reverses a ...

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    13

    Help! I need to reverse a string!!

    Sorry for the lack of comments, but it's not too complicated. I need to make a function that reverses a string inputed by the user. This is what I have so far, and I'm still learning C++, but I can't solve my problem:

    // PROJECT 10-1.CPP
    // By Josh Milewski

    #include <iostream.h>

    char original_string[21], reversed_string[21];
    int x;

    int reverse_string(int original_string)
    {
    for (x = 0; x < 21; x++)
    {
    reversed_string[x] = original_string[21-x];
    }
    return reversed_string[x];
    }

    main()
    {
    cout << "Input a string to be reversed: ";
    cin.get(original_string, 21);
    cout << '\n';
    reversed_string[21] = reverse_string(original_string[21]);
    cout << reversed_string[x] << '\n';
    return 0;
    }

    In Microsoft Visual C++ 6.0, it says this when I try to compile it:

    --------------------Configuration: PROJECT 10-1 - Win32 Debug--------------------
    Compiling...
    PROJECT 10-1.CPP
    X:\PROJECT 10-1.CPP(13) : error C2109: subscript requires array or pointer type
    Error executing cl.exe.

    PROJECT 10-1.OBJ - 1 error(s), 0 warning(s)

    Please help me! Thank you very much!

  2. #2
    Mayor of Awesometown Govtcheez's Avatar
    Join Date
    Aug 2001
    Location
    MI
    Posts
    8,825

  3. #3
    Registered User
    Join Date
    Dec 2004
    Posts
    13
    But can you help me with my simple program? What I mean is, I don't understand those other programs...

  4. #4
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,399
    That's not too bad for a first post, except you should use code tags.

    The posted syntactical error is that your reverse_string function takes a parameter of an int and returns an int. Both should be a char*. You can only use the subscript operator on a pointer. However, that won't solve all of your problems. In fact, fixing that will give you an error on line 23. You might want to read up on arrays.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  5. #5
    Registered User
    Join Date
    Dec 2004
    Posts
    13
    Wait, you said "Both should be a char*." But both what?

  6. #6
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,399
    Both the parameter and the return type of your reverse_string function.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  7. #7
    Registered User
    Join Date
    Dec 2004
    Posts
    13
    Can you tell me exactly what those are? I'm really sorry, but I don't really know the terms.

  8. #8
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,139
    There already is a function which does what you need. It's called strrev. So all you need to do is program your own strrev function.

    void reverse_string( char* string )
    {
    // your task is to
    // find out how long this string is ( hint: it's not neccessarily 21, it can be shorter. look up the strlen function )
    // reverse the first x characters of your string. Don't reverse all 21 because the text entered may be shorter
    }


    This function should reverse the string you gave as a parameter.

    PHP Code:
    int main()
    {
    char text[21];
    cout << "Input a string to be reversed: ";
    cin.get(original_string20);
    cout << '\n';
    reverse_stringtext );
    cout << text << '\n';
    return 
    0;

    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

  9. #9
    Registered User
    Join Date
    Dec 2004
    Posts
    13
    Yes, I know I can do it that way, which would be a lot easier, but I cannot. That is because I need to do this for a school project, and I am required to make my own function called reverse_string to reverse the string. Thank you for your help, though, and please continue to help me.

  10. #10
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,139
    Well then, try to build your own reverse_string function from the header I provided above. Use the comments I added. Feel free to post any questions that arise
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

  11. #11
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,803
    Quote Originally Posted by Josh7289
    Can you tell me exactly what those are? I'm really sorry, but I don't really know the terms.
    Look at this example:

    Code:
    int foo(int bar)
    {
        ...
    }
    The return type in the above example is red. It states (in this example) that the function returns an integer value. The argument/parameter type in the example is in blue. It states that the function expects a single parameter/argument of type integer to be passed into the function.

    Code:
    #include <iostream.h>
    If possible you should be using the iostream header and not iostream.h. This will bring up the issue of namespaces however and at this stage it is perhaps easiest to deal with this by simply putting using namespace std; underneath the #include line.

    Code:
    int main()
    {
        ...
    }
    You should always explicitly put that int return type for the main function.

    Code:
    reversed_string[21] = reverse_string(original_string[21]);
    You should not be calling your function like that. Character strings (character arrays) are declared like reversed_string[21] but when you pass them into functions, you typically just use the array name like reverse_string(original_string). Arrays are indexed starting from 0, so an array holding 21 characters has a valid index from 0 through 20 inclusive. Outside of declaring an array, the syntax you use in the above sample is used to access individual elements of the array (the individual characters in this case) thus reversed_string[0] represents the first character and reversed_string[21] represents the 22nd character which is an invalid index. The same goes for your use of the original_string[21] in the above example.

    Code:
    char original_string[21], reversed_string[21];
    
    
    for (x = 0; x < 21; x++)
        reversed_string[x] = original_string[21-x];
    
    
    cin.get(original_string, 21);
    I would strongly suggest you use a const int variable instead of a hardcoded value here. If in the future you need to change the length of the array, you change it in one single place instead of having to search through your code and replace every 21 with a different value, i.e.:

    Code:
    const int STR_SIZE=21;
    char original_string[STR_SIZE], reversed_string[STR_SIZE];
    
    ...
    etc, etc...
    As stated previously (by nvoigt), your method of reversing the string should take into account the actual length of data stored in your original_string variable and not the full size of the array itself. You also need to deal with the NULL terminating character, copying it to the correct position and not reversing it by mistake. To deal with these issues, you need to find the length of data in the original_string by looping through it and finding the NULL character, your looping variable at this point will give you the index of the NULL character (and also the length). Once you've got the length, you copy the original string (starting at an index of length minus one and moving towards zero) into the reversed string (starting at index 0 and incrementing up). At the end put a NULL character at the end of the reversed string.

    You might still have some issues with how you are passing/returning your variables but here you have some suggestions to think about in the meantime.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  12. #12
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    I know I'm starting to sound like a broken record player these days but...it is a *complete* waste of time trying to write a string reversal function when you really don't even know how to formulate compilable code!

    anyway, here is a similar type of problem - look at how the functions are declared and how they are called in main:


    Code:
    char * uppercase(char * destination, const char * source) {
     size_t i, length = strlen(source);
     for(i = 0; i < length; ++i) {
      destination[i] = toupper(source[i]);
      }
     destination[i] = '\0';
     return destination;
     }
    
    char * uppercase(char * str) {
     return uppercase(str, str);
     }
    
    int main(void) {
     const size_t size = 256;
     char string[size];
     for(;;) { 
      cout << "Input a string to be capitalized: ";
      cin.get(string, size);
      cin.ignore(); // discard any newlines in the input stream
      if(strlen(string) == 0) {
       break;
       }
      uppercase(string);
      cout << string << endl;
      }
     cout << endl; 
     return 0;
     }
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  13. #13
    Registered User
    Join Date
    Dec 2004
    Posts
    13
    Wah! I'm so confused! I'm just a newbie...Here is what I have so far...now...Can you explain in very simple terms and tell me what has to be changed? Like, change it and post it back here? I'm sincerely sorry for the trouble, but please continue to help me:

    PHP Code:
    // PROJECT 10-1.CPP
    // By Josh Milewski

    #include <iostream>
    using namespace std;

    const 
    int size 21;
    char original_string[size], reversed_string[size];
    int x;

    char reverse_string(char original_string)
    {
        for (
    021x++)
        {
            
    reversed_string[x] = original_string[21-x];
        }
        return 
    reversed_string[x];
    }

    int main()
    {
        
    cout << "Input a string to be reversed: ";
        
    cin.get(original_stringsize);
        
    cout << '\n';
        
    reversed_string reverse_string(original_string);
        
    cout << reversed_string[x] << '\n';
        return 
    0;

    Thank you again very much!

  14. #14
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,399
    First examine the logic behind your code. What if I only enter "cat"? What will the output be after it runs through your algorithm? In pseudo-code, your algorithm is:
    Code:
    for each character i in string 1
       character (21 - i) in string 2 = character i in string 1
    Why won't that always work?

    Take another look at nvoigt's post and note his comments about the strlen function.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  15. #15
    Mayor of Awesometown Govtcheez's Avatar
    Join Date
    Aug 2001
    Location
    MI
    Posts
    8,825
    > return reversed_string[x];

    That's not returning what you think it's returning.

Page 1 of 3 123 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 04:45 PM
  3. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 02:23 PM
  5. ........ed off at functions
    By Klinerr1 in forum C++ Programming
    Replies: 8
    Last Post: 07-29-2002, 09:37 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21