0

I need to convert only letters in the string to uppercase and tried this piece of code which throws an error.

   s = "Dense-123-Sparse-999" 
   std::transform(s.begin(), s.end(), s.begin(), std::toupper);

Expected Output: "DENSE-123-SPARSE-999"

"Error: non-void lambda does not return a value in all control paths [-Werror,-Wreturn-type]"

It's throwing an error since there are digits in the input string. How do I write a lambda function that converts characters to uppercase only if they are an alphabet and not a number?

something like this,

transform_if(s.begin(), s.end(), s.begin, [](char c){ if(isalpha(c)return toupper(c);});

since C++ doesnt have transform_if, i'm looking for a one liner with any other commands.

  • 1
    Be aware than in 2020 we have [UTF-8 everywhere](http://utf8everywhere.org/), so consider using libraries like [Qt](https://qt.io/) or [POCO](https://pocoproject.org/). How would you handle some `é` or `à` or `€` or `°` or `§` sign? All of them are on my [AZERTY](https://en.wikipedia.org/wiki/AZERTY) keyboard... – Basile Starynkevitch Dec 10 '20 at 07:24
  • 1
    Do however read some [good C++ programming book](https://www.stroustrup.com/programming.html), and see [this C++ reference](https://en.cppreference.com/w/) – Basile Starynkevitch Dec 10 '20 at 07:29

2 Answers2

0

use a Lambda or a function

char upperize(char c)
{
    return toupper(c);
}
transform(s.begin(),s.end(),s.begin(),upperize);
 
transform(s.begin(),s.end(),s.begin(),[](char s){return toupper(s);});
cout<<s;

you can use isalpha also in addition

0

Answering my own question, figured out transform and for_each with lambda code. works for letters without accents.

for_each(s.begin(), s.end(), [](char &c) { c = (isalpha(c))? toupper(c):c; } ) ;

or

transform(s.begin(), s.end(), s.begin(), [](char &c) { return (isalpha(c))?toupper(c):c ; });

Thanks to Basile's comments educating us on UTF-8, my code failed for below case:

input: "èéêrię"

output: "èéêRIę" (wrong)

will need to get back and search for UTF-8 library usage