如何在控制台输出中将字符从 int 转换为 'appear'?

how to get char casted from int to 'appear' in console out?

我有一个向量,想将整数转换为字符,然后将转换的字符推回向量。 我得到的是向量中的 'invisible' 元素,这不会导致明显的错误,增加 vec.size() 计数,但是在控制台输出期间不显示。我该如何解决这个问题,使它们在向量中显示为普通/'visible' 字符?请参阅下面的代码以演示错误。

#include <iostream>
#include <vector>

int main(int argc, const char * argv[]) {
    
    std::vector<char> test{'a','b'};
    
    int i = 5;
    char h = char(i);
    
    test.push_back(h);
    
    for(auto i: test){
        std::cout << "should be an element ->" << i << '\n';
    }
    std::cout<< "size of vec is -> " << test.size();
    return 0;
    
}

好吧,如果我们检查您正在打印的内容

should be an element ->a
should be an element ->b
should be an element ->♣
size of vec is -> 3

以及数组中那些元素的值

vec[0] = 'a' (thats 97 integer value)
vec[1] = 'b' (thats 98 integer value)
vec[2] = '\x5' (thats 5 integer value)

您正在为您的程序获取正确的输出。 如果要将 5 转换为 char,则应向其添加“0”字符。 所以像

char = i + '0';

将在字符中存储整数值 65 或“5”。

注意:C/C++ 中的字符只是 8 位数字,当您打印它们时,您会从 ascii table 中获得以下字符之一。 ascii table 中的某些字符是非 printable 字符,例如值为 0 的字符为 NULL。 TAB 的值为 8(也 printable 为 '\t')或 ESC 为 27。

感谢所有的建议和意见。为了在这里提供清晰度,这是我试图实现的目标。

#include <iostream>
#include <vector>

int main(int argc, const char * argv[]) {
    
    std::vector<char> test{'a','b'};
    
    int i = 12345 ;
   
    
    std::string w = std::to_string(i);
    
    for(auto i : w){
        test.push_back(i);
        
    }
    
    for(auto i : test){
        std::cout << "element in the vector -> " <<i << '\n';
    }

}