The most portable way to do it is to use the macro toupper() and tolower(). Your program only works if the language is English and uses standard ascii character set. See this page
#include <ctype.h>
int main()
{
char c = 'A';
if( isupper(c) )
c = tolower(c);
else
c = toupper(c);
}
Ancient Dragon
Achieved Level 70
32,269 posts since Aug 2005
Reputation Points: 5,852
Solved Threads: 2,590
Skill Endorsements: 70
@AD: toupper() and tolower() seem to return int and not char.
Also if I recall correctly C++ has new style headers: #include <cctype>.
mvmalderen
Posting Maven
2,612 posts since Feb 2009
Reputation Points: 2,221
Solved Threads: 281
Skill Endorsements: 36
@AD: toupper() and tolower() seem to return int and not char.
That's only to support an argument of EOF (in which case EOF is the return value). If you never expect to pass EOF, such as when it's a stopping condition prior to calling toupper() or tolower(), there's no need to use int. However, your compiler might warn about a narrowing conversion, in which case a cast is justified:
// Option 1: Use int
int foo = tolower(c);
// Option 2: Cast to char
char bar = (char)tolower(c);
Usually the destination is a string, or something along those lines, so the cast is usually the desirable approach for silencing a warning you know is spurious in that specific situation.
And of course, I shouldn't leave without mentioning that the parameter type is int, but the value range is that of unsigned char or EOF. So you generally want to enforce unsigned char on the argument to account for when vanilla char on the implementation is signed:
char foo = (char)tolower((unsigned char)c);
Otherwise you might encounter a weird situation where tolower() and friends do a table lookup using a negative value and all hell breaks loose for no apparent reason. Those are tricky bugs to troubleshoot.
deceptikon
Challenge Accepted
3,499 posts since Jan 2012
Reputation Points: 822
Solved Threads: 481
Skill Endorsements: 58