C++ fread 字符串在控制台输出中缺少第一个字符

C++ fread string missing first character on console output

我正在尝试制作一个基于文件的程序,用户可以在其中输入字符串,该程序会将其保存在主目录中的 .bin 文件中。

这是我目前拥有的:

#include <ostream>
#include <string>
#include <cstdio>
#include <iostream>

using std::string;
using std::cout;

class Ingredient {
private:
    FILE *file;
    string name;
    int nmLen;
    float calories;
    float fat;
    float carb;
    float protein;
    float fiber;
    void writeInfo() {
        nmLen = sizeof(name);
        std::fseek(file, 0, SEEK_SET);
        std::fwrite(&nmLen, sizeof(int), 1, file);
        std::fwrite(&name, sizeof(name), 1, file);
        nmLen = 0;
        name = "";
    }
    string readInfo() {
        std::fseek(file, 0, SEEK_SET);
        std::fread(&nmLen, sizeof(int), 1, file);
        std::fread(&name, nmLen, 1, file);
        return name;
    }
public:
    Ingredient(const string &nm, const float &cal, const float &cb, const float &prot, const float &fib) {
        file = std::fopen((nm+".bin").c_str(), "rb+");
        name = nm;
        calories = cal;
        carb = cb;
        protein = prot;
        fiber = fib;
        if (file == nullptr) {
            file = fopen((nm+".bin").c_str(), "wb+");
            writeInfo();
            cout << readInfo() << "\n";
        }
        else {
            writeInfo();
            cout << readInfo() << "\n";
        }
    }
};

int main() {
    string v1 = "Really Long String Here";
    float v2 = 1.0;
    float v3 = 2.0;
    float v4 = 3.0;
    float v5 = 4.0;
    Ingredient tester(v1, v2, v3, v4, v5);
}

在 .bin 文件的开头,我存储了一个 int 来指示存储的字符串的长度或大小,因此当我调用 fread 时,它将获取整个字符串。现在,只是想测试我是否将字符串写入文件,它会 return 适当。但是我从构造函数的控制台输出中得到的是:

 eally Long String Here

注意确实有一个空白space应该打印字符'R'。这可能是因为我 fseek 不正确吗?

这肯定是错误的std::fwrite(&name, sizeof(name), 1, file);

你需要

std::fwrite(name.c_str(), name.length(), 1, file);