std::cin 数据损坏>>

问题描述

代码

#include<iostream>

int main()
{
    int a=3;
    char ch[5];
    
    std::cout<<&a<<"\n"<<(void*)(ch)<<"\n";
    
    long int k1=strtol("0x70fe14",nullptr,16); // 7405076
    long int k2=strtol("0x70fe00",16); // 7405056
    
    std::cout<<k1<<"\n"<<k2<<"\n";
    
    std::cout<<a<<"\n";
    std::cin>>ch;
    std::cout<<a<<"\n";
    
    std::cout<<ch<<"\n";
        
}

输出

0x70fe14
0x70fe00
7405076
7405056
3
12345678912345678912 // I entered this input for cin>>ch
0
12345678912345678912

我为输入 cin>>ch 输入了 20 个字符,因此它们将从 7405056-7405075 获取内存,那么为什么它会破坏内存地址从 a 开始的变量 7405076 的数据?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)