2017-03-06 80 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); 
相關問題