C++ c++;从字符数组到整数的memcpy

C++ c++;从字符数组到整数的memcpy,c++,C++,我正在尝试将memcpy()从charArray转换为整数变量。复制已完成,但在尝试打印复制的值时,会打印一些垃圾。遵循我的代码 填充有什么问题吗 #include <iostream> #include "string.h" using namespace std; int main() { char *tempChar; string inputString; int tempInt = 3; cout << "enter an

我正在尝试将
memcpy()
charArray
转换为整数变量。复制已完成,但在尝试打印复制的值时,会打印一些垃圾。遵循我的代码

填充有什么问题吗

#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;
}
#包括
#包括“string.h”
使用名称空间std;
int main()
{
char*tempChar;
字符串输入字符串;
int-tempInt=3;
cout输入字符串;
tempChar=newchar[strlen(inputString.c_str())];
strcpy(tempChar,inputString.c_str());
memcpy(&tempInt,tempChar,sizeof(int));

是的,你把记忆搞砸了

使用:
stoi()
将std::字符串转换为整数:

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;
}
#包括
#包括
#包括
int main(){
std::字符串tmpString;
标准::cin>>tmpString;
int const tmpInt(stoi(tmpString));

你如何区分“垃圾”和“非垃圾”你打印出来的东西有什么不对?你在打印值中看到了什么?你真的认为int的内存表示是“代码>133742 < /代码>?不要使用<代码> ATOI < /代码>。如果你必须使用C库函数,使用<代码> Stotol < /C> >,而不是<代码> ATOI 。但是C++中你有更好的替代。你是对的,只是想用C++的方式做。谢谢提示。我想使用MeMpPy类似的行为。我的代码中的错误是什么?你不能。当你输入数字时,它们将作为一个字符序列被内部存储。一个整数有完全不同的内部表示。
函数将一个表示形式转换为另一个。@Prabha Satya:
memcpy
是您的错误。您不能只是“想要”
memcpy
中的一些任意行为。您可以做的是阅读
memcpy
的规范,并意识到它不会也不会做您需要的事情。因此,忘记
memcpy