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

时间:2017-03-06 21:37:45

标签: c++ fwrite fread

我正在尝试创建一个基于文件的程序,用户可以在其中输入字符串,程序会将其保存在主目录中的.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时它会占用整个字符串。现在,只是尝试测试我是否将字符串写入文件,它将适当地返回它。但是我从构造函数的控制台输出中获得的是:

 eally Long String Here

请注意,确实有一个空格应该打印字符'R'。这可能是因为我没有正确地找到这个事实吗?

1 个答案:

答案 0 :(得分:2)

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

你需要

std::fwrite(name.c_str(), name.length(), 1, file);
相关问题