c++ - 为什么在使用 toupper 时将字符转换为数字?
问题描述
小程序
#ifndef _TINYC_H
#define _TINYC_H
#include <string>
#include <vector>
#include <map>
namespace tinyc {
using token_t = std::map<std::string, std::string>;
using tokens_t = std::vector<token_t>;
// const std::string DIGITS = "0123456789";
// const std::string WHITESPACE = " \t\n";
tokens_t tokenize(const std::string& str);
void print_tokens(const tokens_t& tokens);
} // namespace tinyc
#endif // _TINYC_H
主文件
#include <iostream>
#include "tinyc.h"
int main() {
tinyc::tokens_t tokens;
try {
tokens = tinyc::tokenize("()");
} catch (const std::string& e) {
std::cerr << e << '\n';
}
tinyc::print_tokens(tokens);
}
这是整个代码。
在这部分代码中tinyc.h
:
void print_tokens(const tokens_t& tokens) {
if (!tokens.empty()) {
for (const token_t& token : tokens) {
for (const auto& token_pair : token) { // std::pair<...>
for (const char& c : token_pair.first) { // token_pair.first = std::string
std::cout << ::toupper(static_cast<unsigned char>(c));
}
std::cout << ':' << token_pair.second << '\n';
}
}
}
}
在这部分里面,这里是:
std::cout << ::toupper(static_cast<unsigned char>(c)); // Prints random digits. No idea why!? Changed toupper to tolower, un-typecasted it, etc, but nothing worked.
打印随机数字。我不知道为什么。我改为toupper
,tolower
没有对其进行类型转换等,但没有任何效果。
但是由于某种原因,下面的代码可以正常工作:
std::cout << c;
下面的这段代码,std::cout << c
完美地工作并打印实际字符,而不是任何随机数字。
我也尝试(c & ~32)
将其大写,但结果相同,它会打印随机数字。
tokens.push_back({
{ "type", "rparen" },
{ "value", ")" }
});
这就是我在向量中插入地图的方式;我做错了吗?这是导致问题的原因吗?
为什么在应该打印字符时打印随机数字?
解决方案
函数int toupper( int ch );
是从 C 继承的,所以它返回int
. 要正确打印,您需要将类型转换回 char:
std::cout << static_cast<char>(::toupper(static_cast<unsigned char>(c)));
推荐阅读
- glsl - 使用布局 image2D 时 GLSL 输出损坏
- microsoft-graph-api - 发送电子邮件时,MS Teams Graph API 将“发件人”字段返回为空
- jquery - Fiddle jQuery 正在开发旧版本,但不是最新版本?
- mysql - MySQL:无法弄清楚如何使这项工作
- arrays - 构造函数似乎没有正确初始化我的数组
- c# - 如何使用api在谷歌表格中每2个单元格重复一次
- python - 使用python将分时价格转换为范围柱ohlc数据
- git - 简单的 GIT 查询
- python - 在 python 的矢量化函数中使用 Numba 时出错
- wordpress - WordPress插件首先重定向到登录