没有从std :: string到int的合适转换

时间:2015-01-13 15:09:20

标签: c++ c++11

我试图使用标准C库的一些功能但是我得到了这个错误:没有从std :: string到int的合适转换。我刚从C学习C ++。请不要用困难的术语来解释这个问题。

#include <iostream>
#include <string> 
#include <cctype>

using namespace std; 

int main(void)
{
  string s1{ "Hello" }; 
  bool what{ isalnum(s1) }; 
  return 0; 
} 

2 个答案:

答案 0 :(得分:5)

isalnum告诉您单个字符,而不是整个字符串是否为字母数字。

如果要检查字符串是否为字母数字,则需要使用循环查看每个字符:

bool what = true;
for (unsigned char ch : s1) {
    if (!std::isalnum(ch)) {
        what = false;
        break;
    }
}

或算法:

#include <algorithm>

bool what = std::all_of(s1.begin(), s1.end(), 
    [](unsigned char ch){return std::isalnum(ch);});

正如评论中所提到的,使用字符分类功能时会出现许多并发症和死亡陷阱,即使它们看似简单。我认为我的例子避免了大部分内容,但要谨慎行事。

答案 1 :(得分:0)

我发布这个以便C ++这样做的方式也在这里。我更喜欢这种方式,因为它对全局状态的依赖性较小

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;
    }
}

和算法方式:

#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);

注意:您必须将std::isalnum模板专门设为char,否则std::bind也不知道它的约束力。