首页 > 解决方案 > C++ 错误:没有用于调用“toupper”的匹配函数

问题描述

以下代码引发了调用“toupper”错误(C++ 11)的不匹配函数:

string s("some string");
if (s.begin() != s.end())
{
    auto it = s.begin();
    it=toupper(it);
}

这段代码来自 C++ 入门,第五版,第 3 章,关于“介绍迭代器”。

你知道为什么会出现这个错误吗?

标签: c++c++11

解决方案


  1. You need to include the appropriate headers, in this case <string> and <cctype>.
  2. You need to specify the namespaces, in this case std:: (use say using namespace std, but that is not a good idea).
  3. it is not a character. It is an iterator into the string. Think of it as a pointer-like object. When you want to change a character pointed to by p, you would say *p = do_something_with(*p), not p = do_something_with(p) which would change the pointer.

Thus if we write:

#include <iostream>
#include <cctype>

int main()
{
    std::string s("some string");
    if (s.begin() != s.end()) {
        auto it = s.begin();
        *it = std::toupper(*it);
    }
}

then this compiles (GodBolt.org).


推荐阅读