Gianni Mariani wrote:
Rick wrote: For some reason my function to capitalize the first letter in a
string
and keep all the other letters lowercase isn't working. This is what
I have.
string convname(string name)
{
int len;
len = name.length();
name[0] = toupper(name[0]);
for(int i = 0; i < len; i++)
name[i] = tolower(name[i]);
return name;
}
string convname(string name)
{
int len;
len = name.length();
if ( len > 0 )
{
name[0] = toupper(name[0]);
for(int i = 1; i < len; i++)
name[i] = tolower(name[i]);
}
return name;
}
issues:
a) you referenced name[0] even though the string may be 0 length
b) the loop started at position 0 - overwriting the first toupper
assignment.
Another issue that might be visible or not on your system, depending on
the signedness of char: touppoer and tolower want their parameter
converted to an unsigned char. So actually has to be:
string convname(string name)
{
int len;
len = name.length();
if ( len > 0 )
{
name[0] = toupper((unsign ed char)name[0]);
for(int i = 1; i < len; i++)
name[i] = tolower((unsign ed char)name[i]);
}
return name;
}
Oh, and calling length() on a string and then using that for a loop to
iterate through it can be quite inefficient on some implementations
(just the same as strlen for C style strings). You can work around that
by using iterators:
string convname(string name)
{
string::iterato r it(name.begin() );
if (it != name.end())
name[0] = toupper((unsign ed char)name[0]);
while(++it != name.end())
{
*it = tolower((unsign ed char)*it);
}
return name;
}
All code untested, but should mostly work.