Char和int放入同一数组中

Char and int into the same array

本文关键字:数组 int Char      更新时间:2023-10-16

我想将整数和字符存储在同一个数组中。喜欢:EA1001或EB1254它们应该是身份代码。它不一定是一个数组,只是我可以用来将这些字符串存储在一起的东西,否则我很难重复使用它们。谢谢你抽出时间。

不能将它们存储为字符串吗?例如

std::vector<std::string> my_codes;
my_codes.push_back("EA1001");
my_codes.push_back("EB1254");

答案是联合数组。但这可能很危险。

union
{
    char char_var;
    int int_var;
}same_array;

并进行声明:

same_array my_array[1000];

因为int是16或32位,而char是8位。这是表示int和char 的32位区域的唯一方法

最合理的解决方案是使用std::string。从你的问题来看,你似乎只需要持有可以包含数字的字符串:

std::string a = "EA112312";

如果你想要一组,使用std::vector,它的元素是字符串:

std::vector< std::string >vec;
vec.push_back(a);//adding an element to the vector, where a is a string.

实际上,你甚至可以做一些类似的事情:

int a = 'm';
std::cout << (char)a;

从技术上讲,可以将数字和字符存储在int的数组中,但这将是…呃。。。奇怪的