Cant get string::size_type + int to do toupper

65 views Asked by At

I want to use toupper on each char after point . in the string. I tried this code but I an getting a black screen when I start the program if I use + operator.

string fulltext = "my name is John. i have a girlfriend. her name is Anna";

string::size_type idx = 0;
while ((idx = fulltext.find(".")) != string::npos)
{
    if (idx != string::npos)
    {

        fulltext[idx + 2] = toupper(fulltext[idx + 2]);
    }
}
cout << fulltext << endl;
1

There are 1 answers

0
Jonathan Mee On

So it turns out that the only standard defined way to use toupper is to pass an unsigned char: https://stackoverflow.com/a/37593205/2642059 Thus, the best way to do this is with a lambda in a transform, for example you could capitalize string fulltext in it's entirety like this:

transform(cbegin(fulltext), cend(fulltext), begin(fulltext), [](const unsigned char idx){ return toupper(idx); })

Since you want to start at the first '.' and transform works on iterators you could just use find to obtain an iterator to the '.' and use it in the 1st and 3rd arguments of transform: auto it = find(begin(fulltext), end(fulltext), '.') But we can avoid the temporary if we do reverse iteration:

transform(crbegin(fulltext), make_reverse_iterator(find(cbegin(fulltext), cend(fulltext), '.')), rbegin(fulltext), [](const unsigned char idx) { return toupper(idx); });

Live Example