c++ - 从二进制文件输入字符串时出现未处理的异常 | Visual Studio

标签 c++ string unhandled-exception

<分区>

好吧,我对此有点陌生,如果我的问题看起来很愚蠢,我深表歉意。

基本上,我正在尝试将二进制文件读入字符串。
代码:

using namespace std;
fstream words;
words.open("Data/words.bin", ios::binary | ios::in);
string s;
words.read((char*)&s, sizeof(string));
cout << s;
words.close();

编译它给我以下错误:
HangMan.exe 中 0x0FABDF58 (msvcp120d.dll) 处的未处理异常:0xC0000005:访问冲突读取位置 0x052DE6EC。

但是它确实会在抛出错误之前将字符串打印到控制台。

写入文件不会导致任何类型的错误,但读取 char[] 也不会。只有在读入字符串时才会出现此问题。

编辑:

我知道将 string* 转换为 char* 不是一个好主意,但我现在明白了。只是下面的代码有效,所以我假设使用字符串也有效:

#include <string>
#include <fstream>
#include <iostream>
using namespace std;

class foo
{
private: 
int X;
int Y;
int Z;
char C;
public:
    foo(int x,int y,int z, char c): X(x), Y(y), Z(z), C(c){}

void display()
    {
        cout<<X<<endl<<Y<<endl<<Z<<endl<<C<<endl;
    }
};

int main()
{
    fstream out;
    out.open("file.bin", ios::binary | ios::out);
    foo var(1,2,3,'a');
    out.write((char*)&var,sizeof(foo));
    cout<<"var: \n";
    var.display();
    out.close();
    cout<<"var2 before reading: \n";
    foo var2(0,0,0,'z');
    var2.display();
    fstream in;
    in.open("file.bin", ios::binary|ios::in);
    in.read((char*)&var2,sizeof(foo));
    cout<<"var2 after reading: \n";
    var2.display();
    return 0;

}

如果我没理解错,这应该行不通,对吗?

@Rakibul Hasan:我检查了两个问题,没有重复。

最佳答案

string 转换为 char* 是一个非常糟糕的主意:

string s;
words.read((char*)&s, sizeof(string));

你需要先分配内存。如果您想一次读取文件(仅适用于小文件):

size_t fileSize = words.seekg( 0, std::ios::end ).tellg() - words.seekg( 0 ).tellg();
std::vector<char> buf( fileSize );

words.read( &buf[0], buf.size() );

关于c++ - 从二进制文件输入字符串时出现未处理的异常 | Visual Studio ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23949973/

相关文章:

ruby - 如何使用 Ruby 从字符串中删除除数字 ","和 "."之外的所有字符?

error-handling - 有没有办法全局捕获 Blazor 单页应用程序中所有未处理的错误?

c++ - 有效地杀死一个windows进程

c++ - 为什么标准库总是那么复杂?

c++ - 使用结构体从 .txt 文件读取着色器

ios - 匹配字符串模式,包括 Swift 中的变量部分

php - 如何将当前时间与 PHP 中的预设时间进行比较?

c# - 当线程获得未处理的异常时 CLR 退出

c# - 没有YSOD的异常(exception)

python - 具有与 Python 的过滤器和映射相同功能的 C++ 工具