2012-12-26 46 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行为。我的代码中有什么错误? –

相关问题