Question

I'm working on an exercise to store words in a <vector> of strings, then convert all the letters to uppercase, and print out eight words per line. Everything works fine except the toupper() part of my code. Here it all is:

vector<string> words;
string theWords;
string word;

while(cin >> word)
    words.push_back(word);

for(auto &i : words) {
    word = i;
    for(auto &j: word)
        j = toupper(j);
}

int k = 0;
for(auto i : words) {
    cout << i << " ";
    ++k;
    if(k % 8 == 0)
        cout << endl;
}
Was it helpful?

Solution

You're storing your new updated string in word, but you should be updating i

Change this

for(auto &i : words) {
    word = i;
    for(auto &j: word)    // word is updated, but your vector is not
        j = toupper(j);
}

... to this:

for (auto &i : words)      // for every string i in words vector
    for (auto &j : i)      // update your i, not word
        j = toupper(j);

OTHER TIPS

You are converting the temporary string, "word" to upper case, and then discarding it.

string word;

for(auto &i : words) {
    word = i; <<-- here
    for(auto &j: word)
        j = toupper(j);
}

What you need to do is

for(auto &i : words) {
    for(auto &j: i)
        j = toupper(j);
}

Live demo here: http://ideone.com/pwQBQr#

A bit late to the party but here is a version without the extra loop.

for(auto &i : words)
    std::transform(i.begin(), i.end(), i.begin(), ::toupper);

the expression word = i used the string copy constructor. The word is not the one in the vector.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top