首页 > 解决方案 > 为什么在使用 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.

打印随机数字。我不知道为什么。我改为touppertolower没有对其进行类型转换等,但没有任何效果。

但是由于某种原因,下面的代码可以正常工作:

std::cout << c;

下面的这段代码,std::cout << c完美地工作并打印实际字符,而不是任何随机数字。

我也尝试(c & ~32)将其大写,但结果相同,它会打印随机数字。

            tokens.push_back({
                { "type", "rparen" },
                { "value", ")" }
            });

这就是我在向量中插入地图的方式;我做错了吗?这是导致问题的原因吗?

为什么在应该打印字符时打印随机数字?

标签: c++dictionaryvectortoupper

解决方案


函数int toupper( int ch );是从 C 继承的,所以它返回int. 要正确打印,您需要将类型转换回 char:

std::cout << static_cast<char>(::toupper(static_cast<unsigned char>(c)));

推荐阅读