Search code examples
c++functioncapitalizetoupper

Capitalize function not working properly


I'm learning the basics in c++ and I'm trying to write a simple function that capitalizes every letter of each word in a given input. What I've written:

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

int main()
{
    std::cout << "Please enter a sentence: ";
    std::vector<std::string> words;
    std::string x;

    while (std::cin >> x) {
        words.push_back((std::string) x);
    }
    std::cout << std::endl;
    std::vector<std::string>::size_type size;
    size = words.size();

    for (int j = 0; j != size; j++) {
        std::string &r = words[j];
        for (int i = 0; i != r.length(); i++) {
            r = toupper(r[i]);
            std::cout << r << std::endl;
        }
    }
}

returns the first letter of each word capitalized. For example, if I write hello world, the program returns:

H
W

Can someone please tell me what I'm doing wrong and how to fix it.


Solution

  • for (int j = 0; j != size; j++) {
        std::string &r = words[j];
        for (int i = 0; i != r.length(); i++) {
            r = toupper(r[i]);
            std::cout << r << std::endl;
        }
    }
    

    At r = toupper(r[i]);, you are overwriting r to be a string of length 1. So your inner for loop condition becomes false and you get out of the inner loop. So only the first letters of each word are printed out.

    To fix this, save the return value of toupper to some other variable.

    for (int j = 0; j != size; j++) {
        std::string &r = words[j];
        for (int i = 0; i != r.length(); i++) {
            char c = toupper(r[i]);
            std::cout << c << std::endl;
        }
    }