C++ - Inserting and Extracting Characters from an Integer Array
例如:
1 2 3 4 5 6 7 | char mem[100000]; int reg[8]; mem[36] = 'p'; // add char p to our 36th index of our char array reg[3] = (int)mem[36]; // store value of mem[36] into reg[3] |
-
现在,我想在该int数组的索引3处打印char值。
-
到目前为止,我的思想过程已经使我编写了如下代码:
char * c =(char *)reg [3];
cout << * c << endl;
但是在尝试打印出来时,我仍然得到奇怪的值和字符。
据我了解,整数等于4个字符。 从技术上讲,字符是一个字节,整数是4个字节。
因此,我将一个字符作为4个字节存储到我的整数数组中,但是当我将其拉出时,由于我插入的字符只有一个字节,而索引的大小为4个字节,因此存在垃圾数据。
您是否尝试过:
1 2 3 4 5 6 7 | char mem[100000]; int reg[8]; mem[36] = 'p'; // add char p to our 36th index of our char array reg[3] = (int)mem[36]; // store value of mem[36] into reg[3] char txt[16]; sprintf(txt,"%c", reg[3]); // assigns the value as a char to txt array cout<<txt<<endl; |
打印出值" p"
我看不出你是什么问题。 您将char存储到int var中。 您想将其打印回来-只需将值转换为char并打印即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <iostream> int main() { char mem[100]; int reg[8]; mem[36] = 'p'; // add char p to our 36th index of our char array // store value of mem[36] into reg[3] reg[3] = mem[36]; // store value of mem[36] into reg[4] with cast reg[4] = static_cast<int>(mem[36]); std::cout << static_cast<char>(reg[3]) << ' '; std::cout << static_cast<char>(reg[4]) << ' '; } /**************** * Output $ ./test p p */ |
您不应该在这里使用指针。 使用
1 2 | char c = reg[3]; cout << c << endl; |
但是请注意,尝试将