I was trying to write a program which will convert every word(either upper or lower case) in the upper or lower case(depending on which case is max).So here is my program
#include<iostream>
#include<cstring>
#include<cctype>
#include<cstdio>
using namespace std;
int main()
{
char s[101];
int c=0, sm=0, i;
cin>>s;
for(i=0;i<strlen(s);i++)
{
if(s[i]>='A' && s[i]<='Z')
c++;
else
sm++;
}
if(sm>c)
{
for(i=0;i<strlen(s);i++)
{
//cout<<tolower(s[i])<<endl;
putchar(tolower(s[i]));
}
}
else
{
for(i=0;i<strlen(s);i++)
{
//cout<<toupper(s[i])<<endl;
putchar(toupper(s[i]));
}
}
}
But i was surprised to see that if i write these statement
if(sm>c)
{
for(i=0;i<strlen(s);i++)
{
cout<<tolower(s[i])<<endl;
}
}
or
else
{
for(i=0;i<strlen(s);i++)
{
//cout<<toupper(s[i])<<endl;
putchar(toupper(s[i]));
}
}
then it seems that output is in ASCII number.Can anyone explain me these reason.I am new to c++, so not much aware of cout
std::tolower()
and std::toupper()
functions return value is int. And std::cout
print the exact value that appears to it.
So cout<< tolower(s[i])<<endl
print ASCII value of the characters. But when you write putchar(toupper(s[i]))
then putchar()
function automatically converts the ASCII value to characters. That's why you get character as output.
In order to use cout<< tolower(s[i]) << endl
you need to typecast the ASCII value to character.
So write -
cout<< (char)(toupper[i]) <<endl;
cout<< (char)(tolower[i]) <<endl;