2017-10-07 62 views
2

插入和提取特徵例如:C++ - 從一個整數陣列

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 * C =(字符*)REG [3];

    cout < < * c < < endl;

但是當我試圖打印出來的時候,我仍然感到奇怪的值和字符。

從我的理解,一個整數等於4個字符。由於字符在技術上是一個字節,整數是4個字節。

所以我存儲一個字符到我的整數數組作爲4個字節,但是當我將其拉出,有垃圾數據,因爲相比於指數爲4個字節大小我插入字符是隻有一個字節。

+0

你試過簡單地做'的cout << REG [3] << ENDL;'? – frslm

+0

Yes和,代替字符「P」被打印,一個長整型被打印。這是由於我的索引中有垃圾數據,因爲一個字符在技術上只有1個字節,而一個整數是4個字節。 – kabuzashi

回答

0

你不應該在這裏用指針來;它足以與char s到工作:

char c = reg[3]; 
cout << c << endl; 

注意,但是,試圖在int塞進一個char變量時,你可能會失去信息。

+0

您的解決方案是正確的。但我的問題是我沒有直接給我的數組添加一個字符。我試圖展示一個簡單的例子。實際上,我正在將一個字符從一個單獨的char數組添加到這個int數組中。所以我得到一個錯誤,說「char *不能被分配給int。」因此,使其工作的唯一方法是將其轉換爲一個整數,從而使其在數組中具有不同的表示形式。而且因爲這個角色,我有麻煩把角色從陣列中拉出來。 – kabuzashi

+0

告訴我們如何你從其他'char'陣列添加字符。您可能試圖將整個數組分配給int數組中的單個索引。 – frslm

+0

你「的char *不能分配給INT」如果你使用'char's代替'字符*'S作爲溶液中的特定問題就解決了。即使使用額外的代碼,使用'char'似乎也能解決您的問題。有什麼我可能在這裏誤解? – frslm

1

你有沒有嘗試過這樣的:

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值

0

我看不出你有什麼問題。您將char存儲到int var。要打印回 - 只投的價值爲char和打印

#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]) << '\n'; 
    std::cout << static_cast<char>(reg[4]) << '\n'; 

} 

/**************** 
* Output 
$ ./test 
p 
p 
*/