gpt4 book ai didi

c++ - 在文件处理中使用 C++ 字符串

转载 作者:行者123 更新时间:2023-11-28 08:00:04 25 4
gpt4 key购买 nike

如何在文件处理中使用 C++ 字符串?我创建了一个类,该类将 C++ 字符串作为其私有(private)数据成员之一,但在读取文件时出现错误,即使我目前没有对其进行操作,并且在构造函数中使用默认值进行了初始化。写入文件时没有问题。如果我改用 C 字符串但我不想这样做,它工作正常。有办法解决吗?

class budget 
{
float balance;
string due_name,loan_name; //string objects
int year,month;
float due_pay,loan_given;

public:
budget()
{
balance=0;
month=1;
due_name="NO BODY"; //default values
loan_name="SAFE";
year=0;
balance = 0;
due_pay=0;
loan_given=0;
}
.
.
.
};

void read_balance() //PROBLEM AFTER ENTERING THIS FUNCTION
{
system("cls");
budget b;
ifstream f1;
f1.open("balance.dat",ios::in|ios::binary);
while(f1.read((char*)&b,sizeof(b)))
{ b.show_data();
}
system("cls");
cout<<"No More Records To Display!!";
getch();
f1.close();
}

最佳答案

字符串是非 POD 数据类型。您不能通过读/写函数从字符串中读取/写入字符串。

basic_istream<charT,traits>& read(char_type* s, streamsize n);

30 Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1). After constructing a sentry object, if !good() calls setstate(failbit) which may throw an exception, and return. Otherwise extracts characters and stores them into successive locations of an array whose first element is designated by s.323 Characters are extracted and stored until either of the following occurs: — n characters are stored; — end-of-file occurs on the input sequence (in which case the function calls setstate(failbit | eofbit), which may throw ios_base::failure (27.5.5.4)). 31 Returns: *this.

没有关于 std::string 成员如何放置的内容。查看或使用 boost::serialiationhttp://www.boost.org/doc/libs/1_50_0/libs/serialization/doc/index.html当然,您可以写入字符串的大小,然后写入数据,在读取时 - 读取大小,分配此大小的数组,读取此数组中的数据,然后创建字符串。但是使用 boost 更好。

关于c++ - 在文件处理中使用 C++ 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11712343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com