【问题标题】:C++ std::cin Unhandled exception: Access violation writing locationC++ std::cin 未处理异常:访问冲突写入位置
【发布时间】:2011-07-07 05:27:44
【问题描述】:
我在尝试使用 std::cin 时遇到访问冲突。我使用的是char*,它不允许我输入数据。
void Input(){
while(true){
char* _input = "";
std::cin >> _input; //Error appears when this is reached..
std::cout << _input;
//Send(_input);
【问题讨论】:
标签:
c++
std
access-violation
cin
【解决方案1】:
您没有为cin 提供缓冲区来存储数据。
operator>>(std::istream&, std::string) 将为正在读取的字符串分配存储空间,但您使用的是operator>>(std::istream&, char*),它写入调用者提供的缓冲区,并且您没有提供可写缓冲区(字符串文字不可写),所以你遇到了访问冲突。
【解决方案2】:
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;
【解决方案3】:
试试这个:
char _input[1024];
std::cin >> _input;
std::cout << _input;
或者更好:
std::string _input;
std::cin >> _input;
std::cout << _input;