CamelCase in C++

Example for versions Borland C++ Builder 6, Microsoft Visual C++ 9 (2008), g++ 3.4.5

This example is based on character-by-character string processing.

getline reads a string (delimited with end of line) from argument stream. Function tolower works only with single characters, so to convert whole string to lower case it is used with transform function. The latter applies tolower to all elements in the range [text.begin(), text.end()) and stores the results in a range starting with text.begin() again.

After this the string is processed char-by-char. Each character is checked for being alphabetic; if it is, it is appended to the resulting string (converted to upper case if previous character was non-alphabetic); if it is not, it only affects lastSpace (which is true only if last character was non-alphabetic).

isalpha works with both uppercase and lowercase letters, so it was possible not to convert the input string to lowercase, but rather to convert each appended character.

#include <string> 
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
    string text, cc="";
    bool lastSpace = true;
    getline(cin, text);
    transform(text.begin(), text.end(), text.begin(), (int (*)(int))tolower);
    for (int i=0; i<text.size(); i++)
        if (isalpha(text[i])) {
            if (lastSpace)
                cc += toupper(text[i]);
                cc += text[i];
            lastSpace = false;
        else {
            lastSpace = true;        
    cout << cc << endl;
    return 0;