2012-12-26 49 views
-2

我想從charArray做一個memcpy()到一個整數變量。複製完成,但在嘗試打印複製的值時,某些垃圾正在打印。按照我的代碼。從一個字符數組到一個整數的C++ memcpy

是否有任何問題與填充?

#include <iostream> 
#include "string.h" 

using namespace std; 

int main() 
{ 
    char *tempChar; 
    string inputString; 
    int tempInt = 3; 

    cout << "enter an integer number" << endl; 
    cin >> inputString; 
    tempChar = new char[strlen(inputString.c_str())]; 
    strcpy(tempChar, inputString.c_str()); 
    memcpy(&tempInt, tempChar, sizeof(int)); 
    cout << endl; 
    cout << "tempChar:" << tempChar << endl; 
    cout << "tempInt:" << tempInt << endl; 

    return 0; 
} 
+0

你怎麼知道來自 「非垃圾」 的 「垃圾」?你打印什麼錯誤?你期望在印刷的價值中看到什麼? – AnT

+1

你真的認爲int的內存表示就像'133742'嗎? o.O – 2012-12-26 08:13:53

回答

3

是的:你搞砸了內存。

用途:stoi()到的std :: string轉換爲整數:

int tempInt(stoi(inputString)); 

完整的示例:

#include <cstdlib> 
#include <iostream> 
#include <string> 

int main() { 

    std::string tmpString; 
    std::cin >> tmpString; 

    int const tmpInt(stoi(tmpString)); 

    std::cout << tmpInt << std::endl; 

    return 0; 
} 
+1

請勿使用atoi。如果您必須使用C庫函數,請使用'strtol',而不是'atoi'。但在C++中,你有更好的選擇。 – AnT

+0

你是對的 - 只是想用C++的方式來做。感謝提示。 –

+0

我想要使用memcpy的simillar行爲。我的代碼中有什麼錯誤? –

相關問題