How could one convert a string to upper case. The examples I have found from googling only have to deal with chars.
31 Answers
I use this solution. I know you're not supposed to modify that data area.... but I think that's mostly for buffer overrun bugs and null character.... upper casing things isn't the same.
void to_upper(const std::string str) { std::string::iterator it; int i; for ( i=0;i<str.size();++i ) { ((char *)(void *)str.data())[i]=toupper(((char *)str.data())[i]); } } 3 Comments
user93353
I know you're not supposed to modify that data area - what data area are you not supposed to modify?Qaz
This is late, but what on earth? That crazy line can be replaced with
str[i] = toupper(str[i]); perfectly fine (well, not perfectly fine, but it fixes most of the things wrong).dan04
Let's see. You: 1. Define a
void function that takes its argument by value (instead of by reference), making all changes to the string inaccessible outside the function, so that the function is completely useless. 2. Declare an iterator variable that you never use. 3. Cast str.data() to a void* for no good reason. This technically makes it undefined behavior, violating the string aliasing rule.