c++ - C++ 错误:没有用于调用“toupper”的匹配函数
问题描述
以下代码引发了调用“toupper”错误(C++ 11)的不匹配函数:
string s("some string");
if (s.begin() != s.end())
{
auto it = s.begin();
it=toupper(it);
}
这段代码来自 C++ 入门,第五版,第 3 章,关于“介绍迭代器”。
你知道为什么会出现这个错误吗?
解决方案
- You need to include the appropriate headers, in this case
<string>
and<cctype>
. - You need to specify the namespaces, in this case
std::
(use sayusing namespace std
, but that is not a good idea). 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 byp
, you would say*p = do_something_with(*p)
, notp = 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).
推荐阅读
- python - Python用字符串变量定义文件名,包括'\'
- python - node.js 中的 HTTP POST 请求之前如何做一些事情?
- python - 从 python 脚本但在 python 脚本之外运行 python 脚本
- java - 如何在不提供端口号的情况下使用域名访问tomcat应用程序
- python - Django Google Sign in ModuleNotFoundError at /auth/complete/google-oauth2/
- vue.js - How to use same User form component in VueJS 2 for both create and edit User?
- php - 在 Silverstripe 4 中扩展 CsvBulkloader 和 ModelAdmin 类
- mysql - SQL 在多行中计算相同的响应
- c# - HttpClient.SendAsync 调用导致服务端多次触发,返回内部服务器错误
- python - 使用子进程获取 print() 实时输出