I have a class Unit. An object of this class has name, id, budget and other stuff. I want to save the name and the budget in a .txt file at position (i-1). I created struct called Unit2:
struct Unit2{
string name;
int budget;
};
My file.write function:
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();
}
In the main I create object of Unit "a" with name "asd" and budget 120. When I use writeBudgets function an extra characters are added to my file. For example writeBudgets(a,2);
gives me this hÆPasd ÌÌÌÌÌÌÌÌÌÌÌÌ Œ
.What should I do?
You can't write a std::string
like that to a file, as the std::string
object doesn't have the actual string inside itself, but a pointer to the string together with its length.
What you should do is learn more about the C++ input/output library, then you can make a custom output operator <<
for your structure.
You make a custom operator<<
function:
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;
}
With the above function, you can now do eg
Unit2 myUnit = { "Some Name", 123 };
std::cout << myUnit;
and it will print on the standard output
123 Some Name
To read the structure, you make a corresponding input operator function:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.