Char和int放入同一数组中
Char and int into the same array
我想将整数和字符存储在同一个数组中。喜欢: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
的数组中,但这将是…呃。。。奇怪的
相关文章:
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 按字符值访问int数组
- 将 int 数组转换为 std::vector<int*>
- 比较if语句中的数组值和int值
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 在c++中获取两个大int,并将它们存储在数组中
- 声明数组>> int arr[] 时出错;在C++(虽然在 Java 中有效)?
- 有没有办法用 2D 数组 (int) 重载构造函数?
- 当大小未知时,如何迭代指向数组 (int*) 的指针?
- 接受来自函数的二维数组(int 类型)并将其返回到主函数
- 数组 + int 作为一个参数做什么
- 如何制作'bit'数组而不是数组'int'?
- 动态2d数组:int(*ptr)[4]=new int[7][4];
- 为[z][y][x]int定义数组int[x][y][z]有什么好处?
- 用Visual c++编写二维数组int[n][m]到HDF5文件
- 数组int未正确返回
- 将元素推送到动态分配的指针数组int C++
- 如何在另一个数组中插入多维数组(int而非char)
- 将数组(int*)设置为NULL是否释放其占用的内存
- C++如何将数组 int[10] push_back std::vector<int[10]>?