[英]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時它將占用整個字符串。 現在,僅嘗試測試是否將字符串寫入文件中,它將適當地返回它。 但是我從構造函數的控制台輸出中得到的是:
eally Long String Here
請注意,確實存在一個空白區域,該區域應已打印字符“ R”。 這可能是由於我沒有正確查找而造成的嗎?
確保這是錯誤的std::fwrite(&name, sizeof(name), 1, file);
。
你需要
std::fwrite(name.c_str(), name.length(), 1, file);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.