Search code examples
c++stringfor-loopcharchars

How to form a string out of multiple chars in a for loop


The first part of my code is used to receive a single string input from the user and replace certain characters in that word using string class member functions. This part was easy for me to figure out, but I can't seem to figure out how to form a new string out of these changed characters since I will need to use this string for further manipulation later on in my code.

This is problematic since the for loop outputs single char variables that can't be manipulated as a single string.

#include <iostream>
#include <string>

using namespace std;

int main(){
string word;
char letter;
int i;
cout << "Enter a word: ";
cin >> word;
cout << "\n";
    for ( i = 0; i < word.size(); i++)
    {
        if ( word.at(i) == 'e')
        {
            word.at(i) = '3';
        }
        if ( word.at(i) == 'i' )
        {
            word.at(i) = '1';
        }
        if ( word.at(i) == 'x' )
        {
            word.at(i) = '*';
        }
        cout << word.at(i);
    }
    cout << "\n";
}

As my code currently stands, a user might, for example, input the string "cheese" and receive the output ch33s3. However this output is not a string; it is an assortment of chars without a space to separate them. I can't continue my code any further with my for loop output remaining as it currently is.

Edit: I realize now that I already have what I need, but confused myself into thinking the scope wouldn't apply outside my for loop. Thanks for the quick and easy answers.


Solution

  • The variable word contains the altered string and can be manipulated as such. It appears that you already have what you need.

    Also - you may already know this - but you don't need the "at" function to accomplish what you're doing here. You can index the string like an array. For example:

    word[i] = 'e';
    cout << word[i];