c++ std::cin未处理异常:访问冲突写入位置

C++ std::cin Unhandled exception: Access violation writing location

本文关键字:访问冲突 位置 未处理 std cin c++ 异常      更新时间:2023-10-16

当我试图使用std::cin时,我得到了一个访问冲突。我正在使用char*,它不允许我输入我的数据。

void Input(){
while(true){
    char* _input = "";
    std::cin >> _input; //Error appears when this is reached..
    std::cout << _input;
    //Send(_input);

您没有为cin提供一个缓冲区来存储数据。

operator>>(std::istream&, std::string)将为正在读取的字符串分配存储,但是您使用的是operator>>(std::istream&, char*),它写入调用者提供的缓冲区,并且您没有提供可写缓冲区(字符串文字不可写),因此您得到了访问冲突。

char* _input = ""; // note: it's deprecated; should have been "const char*"

_input是指向字符串字面值的指针。输入是一种未定义的行为。使用

char _input[SIZE]; // SIZE declared by you to hold the enough characters

std::string _input;

试试这个:

char _input[1024];
std::cin >> _input;
std::cout << _input;

或更好:

std::string _input;
std::cin >> _input;
std::cout << _input;