CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    Join Date
    May 2006
    Posts
    12

    String Manipulation

    Hello,

    I am trying to learn C++ and running into a problem that I"m at a loss how to get started or basically finished.

    Ok I am building a small C++ console app that takes input from a user and then randomly displays it back with the characters all mixed up.

    I created a character array (ex. char str[21]) for the input using cin.getline but how do I mix up the input and is it possible to remove any spaces the user may have put in? I've been reading online tutorials but they more or less capture input and display exactly what has been entered.

    It's a real newb question, I know. I just need that bump start or direction.

    Thank you.

  2. #2

    Re: String Manipulation

    Code:
    #include <string>
    #include <cstdlib>
    #include <ctime>
    
    std::string MixUpCharacters(const std::string & strData)
    {
        const size_t nLength = strData.length();
        std::string strRetValue;
        std::set<int> arIndices;
        srand(time_t(NULL));
        int nTemp = 0;
        while (arIndices.size() < nLength)
        {
            nTemp = rand() % static_cast<int>(nLength);
            arIndices.insert(nTemp);
        }
        std::set<int>::const_iterator myIterator;
        myIterator = arIndices.begin();
        while (myIterator != arIndices.end())
        {
            if (strData[ *myIterator ] != ' ')
            {
                strRetValue += strData[ *myIterator ];
            }
            ++myIterator;
        }
        return strRetValue;
    }
    Last edited by JamesSchumacher; May 13th, 2006 at 11:32 AM.

  3. #3
    Join Date
    Apr 1999
    Posts
    27,449

    Re: String Manipulation

    Quote Originally Posted by Shasta80
    Hello,

    I am trying to learn C++ and running into a problem that I"m at a loss how to get started or basically finished.

    Ok I am building a small C++ console app that takes input from a user and then randomly displays it back with the characters all mixed up.
    An alternate solution:
    Code:
    #include <string>
    #include <algorithm>
    
    std::string MixUpCharacters(std::string & strData)
    {
        std::random_shuffle( strData.begin(), strData.end() );
        return strData;
    }
    Regards,

    Paul McKenzie

  4. #4
    Join Date
    May 2006
    Posts
    12

    Re: String Manipulation

    Wow thanks Paul and James. Will go try that. I guess if I include the Namespace std, i can remove the std:.

    Thanks again

  5. #5
    Join Date
    May 2006
    Posts
    12

    Re: String Manipulation

    I tried to work with those examples but I must be doing something wrong with passing strings and such, can't get it to compile.

  6. #6
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Re: String Manipulation

    Quote Originally Posted by Shasta80
    I tried to work with those examples but I must be doing something wrong with passing strings and such, can't get it to compile.
    Well...what are the compile errors?

  7. #7
    Join Date
    Sep 2005
    Location
    United States
    Posts
    799

    Re: String Manipulation

    I just compiled this, worked good for me.

    I didn't even know the STL had a random_shuffle function! Thanks Paul

    One small change though. I would pass the string by value instead
    of by reference so the original string is not modified. Just in case
    I want to use it later for some reason.

    Code:
    #include <string>
    #include <algorithm>
    #include <iostream>
    
    using namespace std;
    
    string MixUpCharacters(string strData);
    
    int main(){
    
       string myText = "Hello neighbor";
       string newText = MixUpCharacters( myText );
       cout << myText << endl;
       cout << newText << endl;
    
       cin.get();
    
       return 0;
    
    }
    
    string MixUpCharacters(string strData)
    {
        random_shuffle( strData.begin(), strData.end() );
        return strData;
    }
    Please rate my post if you felt it was helpful

  8. #8
    Join Date
    May 2006
    Posts
    12

    Re: String Manipulation

    Initalizing the variables seems to work as that example but trying it to use it with users input and using character arrays is a bit different. Let me go try something else and see..I need to be able to get rid of spaces as well only true characters.

  9. #9
    Join Date
    May 2006
    Posts
    12

    Re: String Manipulation

    Well I got it too work like this but not sure if I am crossing any boundaries using a mixture of the char and string variable. But I still have to figure out to rmeove any spaces then build the string without any spaces.


    Code:

    #include <iostream
    #include <string>
    #include <algorithm>
    using namespace std;

    // This is where the array size is set.
    const int intArSize = 20

    string MixUpCharacters(string strData);


    int main(int argc, char** argv)

    {


    //Variable to hold initial input
    char charInitInput[intArSize];



    // Display the welcome text
    cout << "Welcome to the text randomizer. This program will take the user's input" << "\n";
    cout << "and display the characters of the input in a random fashion" << ".\n";
    cout << "Have Fun!" << "\n\n";

    // Display
    cout << "Enter your text to a maximum of " << intArSize << ".\n" << "\n\n";

    // The function 'getline' will read the entire inputted text
    // until user hits 'Enter'. The amount of characters read is
    // dependant on the array size, spaces are included as 1 character.
    cin.getline(charInitInput, intArSize);

    string newStr = MixUpCharacters (charInitInput);

    //Displays the initial input
    cout << "Your initial input was " << charInitInput << ".\n" << "\n";
    cout << "The randomized version of your input is " << newStr << "\n\n";

    cout << "Press Any Key To Exit.";
    cin.get();


    }

    string MixUpCharacters(string strData)
    {
    random_shuffle( strData.begin(), strData.end() );
    return strData;
    }
    Last edited by Shasta80; May 13th, 2006 at 03:47 PM.

  10. #10
    Join Date
    Sep 2005
    Location
    United States
    Posts
    799

    Re: String Manipulation

    Why even bother with the char array?
    Just read the input into a string variable
    using the getline() function.

    Like this...
    Code:
    #include <iostream>
    #include <string>
    #include <algorithm> 
    
    using namespace std;
    
    string MixUpCharacters(string strData);
    
    int main(int argc, char* argv[])
    {
    
       //Variable to hold initial input
       string inputText;
    
       // Display the welcome text
       cout << "Welcome to the text randomizer. This program will take the user's input" << "\n";
       cout << "and display the characters of the input in a random fashion" << ".\n";
       cout << "Have Fun!" << "\n\n";
    
       // Display
       cout << "Enter your text: ";
    
       // The function 'getline' will read the entire line of 
       //input text until user hits 'Enter'. 
        getline(cin, inputText);
    
       string newStr = MixUpCharacters(inputText);
    
       //Displays the initial input
       cout << endl;
       cout << "Your initial input was " << inputText << endl;
       cout << "The randomized version of your input is " << newStr << endl;
       cout << "Press Any Key To Exit.";
    
       cin.get();
       return 0;
    
    }
    
    string MixUpCharacters(string strData)
    {
       random_shuffle( strData.begin(), strData.end() );
       return strData;
    }
    Last edited by dcjr84; May 13th, 2006 at 07:25 PM.
    Please rate my post if you felt it was helpful

  11. #11
    Join Date
    May 2006
    Posts
    12

    Talking Re: String Manipulation

    hmm Good question...But I have added some other stuff and 'strlen' does not work on the variable being a string.

    hmmm. I just used str.length()
    Last edited by Shasta80; May 13th, 2006 at 09:57 PM.

  12. #12
    Join Date
    Sep 2005
    Location
    United States
    Posts
    799

    Re: String Manipulation

    Yes, this is the beauty of using the std::string

    You don't need to know or keep track of how long the string is
    because that information is all stored automatically within the
    string itself and can be retrieved using the length() member function.
    This is why using strings is recommended over char arrays whenever
    possible.

    No need for the strlen() function with strings.
    Please rate my post if you felt it was helpful

  13. #13
    Join Date
    May 2006
    Posts
    12

    Re: String Manipulation

    Really appreciate everyones help.

  14. #14
    Join Date
    May 2006
    Posts
    12

    Exclamation Re: String Manipulation

    Have a bit of an issue with this program. Firstly because I'm using the random function I need at least 4 characters to seed so I put a loop in the input to only continue when 4 or more characters are entered. The problem is if you hit the space bar, that counts as a character. So hitting the space bar 4 times ends up with a blank result of course.

    Anyway to disable the space bar during input?

  15. #15
    Join Date
    May 2006
    Posts
    11

    Re: String Manipulation

    Quote Originally Posted by Shasta80
    Have a bit of an issue with this program. Firstly because I'm using the random function I need at least 4 characters to seed so I put a loop in the input to only continue when 4 or more characters are entered. The problem is if you hit the space bar, that counts as a character. So hitting the space bar 4 times ends up with a blank result of course.

    Anyway to disable the space bar during input?
    stopping a space being entered in cin is something I have never looked at but anyway if you captured each character as the user enters the string you can disregard spaces and copy all good characters into a buffer.

    I know there is a function called getch() which returns the byte value of each character, not sure which header to include tho.

    in a loop you could retrieve characters untill the enter key is pressed or something. and simply disregard spaces

    Code:
    char c_Return = getch();
    
    if( c_Return != char( ' ' ) ){
    
        //Add character to buffer
    }
    Last edited by is.chris; May 15th, 2006 at 12:24 AM.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured