Thread: reversing a character string

  1. #1
    Registered User
    Join Date
    Nov 2004
    Posts
    5

    Question reversing a character string

    I am not asking anyone to write my program for me. I want to get that out upfront. I just desperately need some pointers.

    This is what I was assigned: "Read in a string of maximum 11
    characters (including the \0 at the end) and whatever is typed in, reverse it using a function". But we cannot use outside functions, we have to code it out.

    My pseudocode looks something like this:
    1. Get word from end user
    2. Use a function to find \0 & reverse the word into a new string
    4. output reversed string

    I am trying to use a FOR loop, but I cannot figure out how to tell it to start with \0 and then go backwards. I have tried using a counter, but I still haven't figured out how to tell it 'start with i being \0; end when i is 0; and decriment by 1'. I know that finding the \0 is the key.

    This is the first programming class I have taken and until now I have grasped things fairly easily. Whether it is the concept, not being able to concentrate (anyone who's had a tooth cut out and reacted t the numbing meds and then the pain meds might be able to understand) or both, but I am very overwhelmed at the moment. I have tried google, but everything I find tends to use other libraries and functions that automatically reverse the string...but nothing that has helped me figure out how to do this. Can anyone help please?

    Thanks
    Heather

  2. #2
    Arggggh DeepFyre's Avatar
    Join Date
    Sep 2004
    Posts
    227
    what are you storing the input as?
    Keyboard Not Found! Press any key to continue. . .

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Ok there are a couple ways to do this. I'm going to describe what I think might be the easist way for you.

    Declare a variable that will store the index of the array, this variable should have a lifespan of the function.

    Start with the first character and go through the array till you find '\0' and then stop.
    Use the variable to keep track of your position.
    Since you are now at the '\0' you want to back up one spot by subtracting one from the variable.
    Use a for loop that will terminate when the variable is less than 0. Each time through decrement one from the variable. In the body of the loop display the character.

  4. #4
    Software Developer jverkoey's Avatar
    Join Date
    Feb 2003
    Location
    New York
    Posts
    1,905
    Hey Heather, welcome to the boards.

    What you'll need to do is use some basic pointer arithmetic.

    For example, say we have a string as such:

    char myString[12];

    myString is a char pointer (char*) that points to a block of memory that contains 12 bytes, which is the array. myString just points to the first of these twelve bytes.

    So, basically, here's a more graphical example:

    Code:
    0     1     2     3     4     5......11
    ^                                    ^
    |                                    |
    myString points here                 |
                                         |
              This is the end of the array
    So, each of those numbers is an individual char* value. myString itself is a char* pointing to the zero'th index.

    char* ptr=myString;

    ptr now points to the zero'th index now.

    Now, if we increment ptr, we move ahead one byte in the array, so initially ptr pointed to slot 0, if we do ptr++, it now points to slot 1. Get where I'm going with this?

    So, to test the value of a character at any positition, you need to dereference the ptr pointer, like so:

    char val=*ptr;

    now say the string was "MyCat"

    if ptr pointed to slot 1 and we dereferenced it, we'd get the char value 'y'

    So, in other words, you want to keep incrementing (for loop wouldn't work in this case...) until you hit the null terminator. This is the end of your string.

    And that's as far as I'll go, hopefully that helps clear up the matter a bit, and I don't want to give too much as you said you just want pointers.

    -Hope that helps

  5. #5
    Registered User manofsteel972's Avatar
    Join Date
    Mar 2004
    Posts
    317
    If the maximum buffer is 11 characters then just set it to 11 then decrement till you find \0. then decrement to 0 printing each character.

    [edit]
    on second thought this wouldn't work because if you read in different strings mulitiple times
    if the first string is 11 and the second string is only 9 the \0 character will still be in the buffer from the previous string so it is better to count upward to the first \0. The only way the above would work is if you cleared the buffer before each input.
    Last edited by manofsteel972; 11-14-2004 at 09:05 PM.
    "Knowledge is proud that she knows so much; Wisdom is humble that she knows no more."
    -- Cowper

    Operating Systems=Slackware Linux 9.1,Windows 98/Xp
    Compilers=gcc 3.2.3, Visual C++ 6.0, DevC++(Mingw)

    You may teach a person from now until doom's day, but that person will only know what he learns himself.

    Now I know what doesn't work.

    A problem is understood by solving it, not by pondering it.

    For a bit of humor check out xkcd web comic http://xkcd.com/235/

  6. #6
    Arggggh DeepFyre's Avatar
    Join Date
    Sep 2004
    Posts
    227
    got a question, could you do this using strings
    I dont know too much about strings.
    Keyboard Not Found! Press any key to continue. . .

  7. #7
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    if you mean std::string then yes you could DeepFyre. Its pretty much the same process. std::string has a size() function that tells you how many characters are in the string and then you can use operator[] to access the individual characters. There are other ways but I'll leave that to you

  8. #8
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    Yes, I'm sure you could do this using the C++ string class, but since the assignment specifies a null terminated array, it sounds like C-style strings were a requirement.

    edit: Oh, and welcome to the boards, Heather.
    Last edited by sean; 11-14-2004 at 09:16 PM.

  9. #9
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Yeah, you could do it using strings (STL strings). The easiest way would probably be to use a reverse iterator to copy from back to front.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  10. #10
    Arggggh DeepFyre's Avatar
    Join Date
    Sep 2004
    Posts
    227
    oh ok, thanks
    Keyboard Not Found! Press any key to continue. . .

  11. #11
    Registered User
    Join Date
    Nov 2004
    Posts
    5
    Thanks for input ya'll. I think I need to take a break for a half hour or so before I look at it again because my mind is reeling and nothing is making sense. I have been looking at the posts and looking at my book and looking at my program and I deleted everything beyond asking for input fom the user. I am feeling incredibly stupid with this right now. Nothing is making sense to me at this point. *sigh* aren't pain pills such fun....bleh!!!!!!!

  12. #12
    Registered User manofsteel972's Avatar
    Join Date
    Mar 2004
    Posts
    317
    Its ok HConn I know how you feel. I get the same way with certain problems. The trick is to just break it down into smaller problems.

    you know you need to read in a string with max of 11 characters so you have a
    input->string[11];

    lets say the word is good
    string | g | o | o | d | \0 | * | * | * | * | * | * |
    index 0 1 2 3 4 5 6 7 8 9 10

    now you want to print the string in reverse so using what we know

    all elements in an array are stored sequentially so we need to index through the array comparing all the elements with what we want to find in this case \0
    int index=0;
    compare string[index] == '\0' (if false then increment index to next element) (if true then decrement index and print element repeat until index ==0);
    "Knowledge is proud that she knows so much; Wisdom is humble that she knows no more."
    -- Cowper

    Operating Systems=Slackware Linux 9.1,Windows 98/Xp
    Compilers=gcc 3.2.3, Visual C++ 6.0, DevC++(Mingw)

    You may teach a person from now until doom's day, but that person will only know what he learns himself.

    Now I know what doesn't work.

    A problem is understood by solving it, not by pondering it.

    For a bit of humor check out xkcd web comic http://xkcd.com/235/

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Another way to do this would be to simply search the forum for the answer, because this is a common homework question which gets asked ALL THE TIME.

    Quzah.
    Hope is the first step on the road to disappointment.

  14. #14
    Registered User manofsteel972's Avatar
    Join Date
    Mar 2004
    Posts
    317
    If it is an assignment it is probably better she didn't do a search since the answer would be right there for her to copy? I would think it would be better for her towork it out on psudo code then to see a finished algorithm but that is just my opinion.
    "Knowledge is proud that she knows so much; Wisdom is humble that she knows no more."
    -- Cowper

    Operating Systems=Slackware Linux 9.1,Windows 98/Xp
    Compilers=gcc 3.2.3, Visual C++ 6.0, DevC++(Mingw)

    You may teach a person from now until doom's day, but that person will only know what he learns himself.

    Now I know what doesn't work.

    A problem is understood by solving it, not by pondering it.

    For a bit of humor check out xkcd web comic http://xkcd.com/235/

  15. #15
    Registered User
    Join Date
    Nov 2004
    Posts
    5
    I am trying...honest I am....this is what I have so far BUT this is my output....HELP theres 2 problems with this....
    1)it isn't looping like I need it to
    2) I need to figure out how to assign all the letters in reverse order to a new string called for lack of better name at the moment reverse (which may not be possible until I put this in a function at the bottom I swear I am not usually this blonde @ self.

    picture of output

    Here is my code
    Code:
    //Heather Conn
    //Program 7
    //This program will read in a word of 1-10 letters and output the word reversed
    
    #include <iostream>
    #include <iomanip>
    #include <fstream>
    
    //Declare std
    using std::cout;
    using std::cin;
    using std::endl;
    using std::ios;
    using std::cerr;
    using std::ofstream;
    
    
    //Start the program
    int main ()
    {
    
    //Declare the variables
    	char string1[10];
    	int index;
    	//char reverse[]; commented out till I do the function
    	
    
    //Open the file for output
    	ofstream data_out ("output.txt", ios::out);
    
    //Error routine if file can not be created
    	if (!data_out) {
    		cerr << "File could not be opened" << endl;
    		exit (1);
    	}
    
    
    //Describe program to user
    	cout << "This progam will output any word consisting of 1-10 characters in reverse." << endl;
    	data_out << "This progam will output any word consisting of 1-10 characters in reverse." << endl;
    
    //Get word and output to file
    	cout << "\nPlease enter a word 1-10 characters in length: ";
    	cin >> string1;
    	data_out << "\nThe word is: " << string1 << endl;
    
    //Initialize index
    	index=10;
    
    /*Set up loop..i know this is borked...i just haven't figured out how to do what I want...this doesn't keep looping back to the IF*/
    	while (index >= 0){
    
    		if (string1[index]=='\0'){
    		--index;
    		cout << string1[index] << endl;
    		}
    
    		else {
    			if (string1[index]!='\0'){
    				--index;
    			}
    		}
    	}
    
    
    //End program
    		return 0;
    
    }
    Also I have looked at posts concerning strings, but it didn't help me UNDERSTAND what I am doing and I don't want to just copy something off a forum and hand it in not knowing what it did or why it did it. That's a waste of my money (for the class) and a waste of my teacher's time and serves me no purpose. *exit soapbox now*

    Sorry I am frazzled and tired and in pain and I wish I could figure this out. I feel I am a little closer...but still so far away. ERGGH
    Last edited by HConn; 11-14-2004 at 11:51 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  3. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  4. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  5. Reversing a String
    By ToasterPas in forum C++ Programming
    Replies: 10
    Last Post: 08-14-2001, 12:20 PM