C++ 从结构写入文件时的额外字符
我有一个班级单元。此类的对象具有名称、id、预算和其他内容。我想将名称和预算保存在位置(I-1)的.txt文件中。我创建了名为Unit2的结构:C++ 从结构写入文件时的额外字符,c++,file,character,C++,File,Character,我有一个班级单元。此类的对象具有名称、id、预算和其他内容。我想将名称和预算保存在位置(I-1)的.txt文件中。我创建了名为Unit2的结构: struct Unit2{ string name; int budget; }; My file.write函数: void writeBudgets(Unit name,int i) { ofstream file("C:\\Users\\User\\Desktop\\budgets.txt"); Unit2 p
struct Unit2{
string name;
int budget;
};
My file.write函数:
void writeBudgets(Unit name,int i) {
ofstream file("C:\\Users\\User\\Desktop\\budgets.txt");
Unit2 p;
p.name = name.getName(); //get name from the class Unit
p.budget = name.getBudget(); //same for budget
file.seekp((i-1)*sizeof(Unit2));
file.write(reinterpret_cast<char*> (&p),sizeof(Unit2));
file.close();
}
std::ostream& operator<<(std::ostream& os, const Unit2& unit)
{
// Write the number
os << unit.budget;
// And finally write the actual string
os << unit.name << '\n';
return os;
}
std::istream& operator>>(std::istream& is, Unit2& unit)
{
// Read the number
is >> unit.budget;
// The remainder of the line is the name, use std::getline to read it
std::getline(is, unit.name);
return is;
}
void writeBudgets(单位名称,int i){
流文件(“C:\\Users\\User\\Desktop\\budgets.txt”);
第2单元p;
p、 name=name.getName();//从类单元获取名称
p、 budget=name.getBudget();//与预算相同
文件编号:seekp((i-1)*sizeof(Unit2));
write(reinterpret_cast&p),sizeof(Unit2);
file.close();
}
在主体中,我创建了名为“asd”和budget 120的单元“a”的对象。使用writeBudgets函数时,会向文件中添加额外的字符。例如
writeBudgets(a,2)
给了我这个hÆPasdÌÌÌÌÌÌÌŒ
。我该怎么办?你不能像这样将std::string
写入文件,因为std::string
对象本身没有实际的字符串,而是一个指向字符串及其长度的指针
你应该做的是更多地了解C++库,然后你可以定制输出操作符<代码> > p>你不能像文件那样写一个<代码> STD::String ,因为
你应该做的是更多地了解C++库,然后你可以定制输出操作符<代码>确保你的字符串是空的(即在结尾附加0)确保你的字符串是空的(即在结尾附加0)我怎么能写下至少在特定位置的预算?“@user3163546使用一些示例输出和输入运算符更新了我的答案
std::getline(is>>std::ws,unit.name)
-std::getline()
不会跳过前导空格。我如何使用“@user3163546使用一些示例输出和输入运算符更新了我的答案std::getline”,至少在特定位置写入预算(is>>std::ws,unit.name)
-std::getline()
不跳过前导空格。
123 Some Name
std::istream& operator>>(std::istream& is, Unit2& unit)
{
// Read the number
is >> unit.budget;
// The remainder of the line is the name, use std::getline to read it
std::getline(is, unit.name);
return is;
}