[英]C++ fread string missing first character on console output
I'm trying to make a file based program where a user can enter strings, and the program would save it in a .bin file in the main directory. 我正在尝试制作一个基于文件的程序,用户可以在其中输入字符串,该程序会将其保存在主目录的.bin文件中。
This is what I currently have: 这是我目前拥有的:
#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);
}
In the beginning of the .bin file I store an int to indicate the length or size of the string stored so when I call fread it would take the entire string. 在.bin文件的开头,我存储了一个int来指示存储的字符串的长度或大小,因此当我调用fread时它将占用整个字符串。 Now, just trying to test if I write strings into file, it would return it appropriately.
现在,仅尝试测试是否将字符串写入文件中,它将适当地返回它。 But what I get from the console output from my constructor is this:
但是我从构造函数的控制台输出中得到的是:
eally Long String Here
Note that there is indeed a blank space that should have printed the character 'R'. 请注意,确实存在一个空白区域,该区域应已打印字符“ R”。 Is this possibly due to the fact that I'm not fseek-ing correctly?
这可能是由于我没有正确查找而造成的吗?
for sure this is wrong std::fwrite(&name, sizeof(name), 1, file);
确保这是错误的
std::fwrite(&name, sizeof(name), 1, file);
. 。
you need 你需要
std::fwrite(name.c_str(), name.length(), 1, file);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.