Reputation: 4024
I was trying to use some of the function of standard C library but I got this error: no suitable conversion from std::string to int. I have just stepped into learning C++ from C. Please don't over explain this thing with difficult terms.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main(void)
{
string s1{ "Hello" };
bool what{ isalnum(s1) };
return 0;
}
Upvotes: 0
Views: 3351
Reputation: 5138
I'm posting this so that the C++ way of doing this is also here. I prefer this way as it has less dependency on global state
std::locale locale; // grab the current global locale locally, may lock
bool what = true;
for (auto ch : s1) {
if (!std::isalnum(ch, locale)) {
what = false;
break;
}
}
and the algorithm way:
#include <algorithm>
#include <locale>
#include <functional>
std::locale locale; // grab the current global locale locally, may lock
auto isalnum = std::bind(std::isalnum<char>, std::placeholders::_1, locale);
bool what = std::all_of(s1.begin(), s1.end(), isalnum);
Note: you have to specialize the std::isalnum
template to char
because otherwise std::bind
has no idea what it's binding too.
Upvotes: 0
Reputation: 254581
isalnum
tells you whether a single character, not a whole string, is an alphanumeric.
If you want to check whether the string is alphanumeric, you'll need to look at each character, either with a loop:
bool what = true;
for (unsigned char ch : s1) {
if (!std::isalnum(ch)) {
what = false;
break;
}
}
or an algorithm:
#include <algorithm>
bool what = std::all_of(s1.begin(), s1.end(),
[](unsigned char ch){return std::isalnum(ch);});
As mentioned in the comments, there are many complications and deathtraps when using character classification functions, even though they appear to do something simple. I think my examples avoid most of them, but tread carefully.
Upvotes: 5