Bayaz Bayaz - 11 days ago 7
C++ Question

Iterating through characters of a string stored in a vector to replace characters C++

So we got an optional assignment in our C++ class. The assignment is basically this:

Write a program that holds a string of at least 8 words.
Do the following:

1. Replace the letters of first word with '?'
2. Turn the letters of the last word to uppercase


We did not yet study vectors in our class.

When I first read the assignment, storing the strings to a vector seemed like a good idea so I went with it.

To replace the characters with a '?' I used a for loop. I know that this would not work if I only had to change only certain characters or every other character to a '?'.

My issue is with converting chars of a string to uppercase.
My thought process was: for loop iterates through all chars in the last word, if the char is lowercase it gets turned to uppercase, if it is already uppercase it does not change.

I believe that my approach could work for this problem, I just maybe did not express myself correctly or I made a silly error somewhere. Could anyone assist me or push me in the right direction?
What other options are there to iterate through all chars of a string stored in a vector? Is there another approach that might work better for this? Thank you for your time.

#include <vector>
#include <cctype>
#include <string>
#include <iostream>

using namespace std;

vector<string>words;

//stores words to vector words
void storeWords()
{
cout << "Input 8 words: " << endl;
string s = " ";
for(int i=0; i<=7; i++)
{
cin >> s;
words.push_back(s);
}
}
//prints our words
void printWords()
{
cout << "\n Words stored in vector: " << endl;
for (const string s : words)
cout << s << endl;
}

//replaces chars of the first word with a '?' sign
void replace1(vector<string>&v)
{
cout << "\nReplaced characters of the first word " << words[0] << " with '?'" << endl;
for (char c : words[0])
cout << "?";
}

void replace2(vector<string>&v)
{
for (char c : words[7])
{
if(islower(c))
c = toupper(c);
}
cout << endl;
cout << words[7]<<endl;
}


int main()
{
storeWords();
printWords();
replace1(words);
replace2(words);

return 0;
}

Answer

c = toupper(c) will assign c the uppercase value. However, changing c will not change what's inside words[7]. You can get around this by referencing the char directly (char &c).

void replace2(vector<string>&v)
{
    for (char &c : words[7]) {
        c = toUpper(c);
    }
    cout << endl;
    cout << words[7]<<endl;
}

Also note that your requirements are to hold a string of at least 8 words. So words[7] will probably end up looking like words[words.size() - 1].

Comments