Reputation: 57
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int i;
char s[100];
cin >> s;
for(i=0;i<strlen(s);i++)
{
if(islower(s[i])==1)
{
s[i]=strupr(s[i]);
cout << s[i];
}
else
{
s[i]=strlwr(s[i]);
cout << s[i];
}
}
return 0;
}
These two lines i.e. s[i]=strupr(s[i])
and s[i]=strlwr(s[i])
shows this error :
invalid conversion from char to char*.
How can I solve it? Thank you.
Upvotes: 0
Views: 662
Reputation: 7017
You should use these two instead:
s[i] = std::toupper(s[i]);
s[i] = std::tolower(s[i]);
Remember to include <cctype>
. Here is a link to some documentation of std::toupper and std::tolower.
The problem is that strupr
and strlwr
work on entire strings, not single characters. Moreover, they operate in-place and they are non standard.
Side note:
You could consider using a std::string s
instead of char s[100]
, this removes the current overflow opportunity in cin >> s;
.
Update:
It is possible to use std::transform like so:
std::transform(std::begin(s), std::end(s), std::begin(s), [] (char c) { return std::islower(c) ? std::toupper(c) : std::tolower(c); });
One benefit of using std::begin(s)
and std::end(s)
is that it works for both std::string
, std::vector
and even char[100]
.
Upvotes: 7
Reputation: 4096
strupr
and strlwr
expect a char*
and not a char
as their parameter.
You would need to pass the whole s
array instead of s[i]
Alternatively use the std::toupper
and std::tolower
which would allow you to do each character in turn.
You can also get rid of the raw loop by using std::transform and a predicate or lamda
char InvertCase(char c)
{
return islower(c) ? std::toupper(c) : std::tolower(c);
}
std::transform(s.begin(), s.end(), back_inserter(result), InvertCase);
Upvotes: 3
Reputation: 4430
strupr()
modifies in place its string (that is, char[]
) argument replacing all lowercase letters with uppercase. I think that you are confusing strupr()
with toupper()
.
Note that by using strupr()
or toupper()
you are making an implicit assumption that each char
represents a character; this is not true for multi-byte encodings such as UTF-8.
Upvotes: 2
Reputation: 1135
sdtrupr
and strlwr
take char * as an argument. To convert a single character use tolower
and toupper
Upvotes: 2