Converting characters in strings to uppercase not working

106 views Asked by At

I have this C++ code(Which I will explain below):

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

using namespace std;
int main()
{
    // part 1
    cout << "Write many words separated by either newlines or spaces:"<< endl;
    string word;
    vector<string> v;
    while(cin >> word){
        if(word == "quit"){
            break;
        }
        else{
        v.push_back(word);
        }
    }
    //part 2
    for(string x:v){
        for(char &j:x){
            j = toupper(j);
        }
    }
    //part 3
    for(string x:v){
        cout << x << endl;
    }

    return 0;
}

What I am trying to do is get a sequence of strings and convert each character in the string to uppercase and output the strings back. I want to use vectors for this as I am studying it. In the part 1, I get strings from the standard input and store them in a string vector. I write "quit" to break out of the loop and begin capitalising the letters in each string. The problem is with part 2,obviously. What I am trying to do there is this: 1- Get a string as we loop. 2 Once we have a string, get a character in that string and transform it into uppercase.Do this for all the characters. 3-Do this for all the strings.

When I compile it, I get all correct except the strings being capitalised. I am really confused D:

1

There are 1 answers

1
Columbo On BEST ANSWER
for(string x:v){
    for(char &j:x){
        j = toupper(j);
    }
}

You take every character out of the string by reference, but you take the string by value. Try

for (string& x : v){
    // […]
}

Note that with C++1Z we will be able to use terse range-based for loops, making life a lot easier:

for (x : v) {   // Captures by reference automatically
    // […]
}