Thomas Sampson


1 Comment

C++ String to Uppercase

In my project today I was taking the name of a user and then usig that to generate a data file e.g. “fred.dat”. I decided that I needed to keep the same data file for each user, regardless of how they entered there name .This name was not a username and could be writtin in any mixture of upper / lower case.

To resolve this I decided to make the filenames for each player uppercase when saved and loaded, e.g. FRED.dat but I couldn’t find any easy way to do so. The toupper() function I am familiar with only works on characters so I designed the following simple function to convert a string to uppercase.

NB:- Here I use the string data type, not c string.The resultant string can ofcourse be converted to c string by adding the post function .c_str()

————————–

string toUpperString(string text)
{
string toReturn(text); // duplicate input for manipulation

for(int i=0;i<text.length();++i) // for each character in string
{
toReturn[i]=toupper(text[i]); // convert char to uppercase
}

return toReturn; // return in upper case
}

Please correct me if there is a simpler way to implement this but for now this works a treat.

Advertisements