2017-03-06 79 views
0

我试图制作一个基于文件的程序,用户可以在其中输入字符串,程序会将它保存在主目录中的.bin文件中。C++ fread字符串缺少控制台输出上的第一个字符

这是我目前有:

#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); 
} 

在我保存一个int表示字符串的长度或大小.bin文件的开头存储,因此当我打电话FREAD它将采取整串。现在,试图测试我是否将字符串写入文件,它会适当地返回它。但我从我的构造函数输出的控制台中看到是这样的:

eally Long String Here 

注意,这里确实是一个应该打印的字符“R”空格。这可能是因为我没有正确的认识?

+0

每当你执行任何类型的读操作,必须始终检查读取成功,并以某种方式处理任何故障。 –

+0

第一个问题 - 文件中是否有正确的数据? – pm100

+0

您不能以这种方式序列化/反序列化“字符串”。 –

回答

2

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

你需要

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