从文本文件中读取已创建的结构类型时遇到问题

Having trouble reading in created struct types from a text file

本文关键字:类型 结构 遇到 问题 创建 文件 文本 读取      更新时间:2023-10-16

我正在尝试从.txt文件中读取信息,并将信息放入以前创建的结构类型中。

以下是结构定义:

struct String
{
   const char* text;
   int sz;  //length of string not including null terminator
};

这是给我错误的代码(这只是一个巨大的错误,最后它说"无法将‘title’转换为‘signed char*’">

CDs* createCDs(const char* file_name)
{
   ifstream input_file;
   input_file.open(file_name);
   String* artist;
   input_file >> artist;
   String* title;
   input_file >> title;

此外,正在读取的信息只是文本。如有任何帮助或意见,我们将不胜感激。

两个变量artisttitle指针,而不是对象。因此,如果你做了以下事情,你就不会看到同样的行为:

String artist;
input_file >> artist;

当然,假设您有适当的operator>>()过载(我稍后会对此进行解释(。

当您尝试读取指针时,会出现错误,因为编译器找不到流提取运算符(operator>>()(的重载,该重载将指向String的指针作为右手参数。您之所以在底部看到"cannot convert 'title' to type 'signed char*',是因为编译器列出了所有候选重载以及它们在尝试将artisttitle转换为右侧参数时发出的相应错误。


如果需要使用指针,则必须将其初始化为有效对象。您必须取消引用指针以获得对其所指向对象的引用,这样流就可以将数据读取到其中:

String* artist = new String;
input_file >> *artist;

但话说回来,实际上并不需要指针。这可以通过将对象保留在堆栈上来实现:

String artist;
input_file >> artist;

如果出于某种原因,您仍然需要使用指针,那么您必须记住取消分配指针指向的内存(如果分配给使用new创建的数据(。使用delete:执行此操作

// when you are finished using the data artist or title points to
delete artist;
delete title;

或者,您可以使用std::unique_ptr<String>std::unique_ptr<>是一个容器,当它超出范围时,它将为您管理内存,因此您没有必要自己解除分配资源:

{
    std::unique_ptr<String> title;
    // ...
} // <= the resource held by title is released

如果编译器不支持std::unique_ptr<>,这是一个新的(C++11(对象,则可以使用std::shared_ptr<>


当将流I/O语义合并到用户定义的类中时,传统的做法是提供流运算符的重载,该重载随后将数据提取到类的数据成员中。它允许语法:

X x;
istream_object >> x;
ostream_object << x;

从您向我们展示的内容来看,我不认为您为输入流对象提供了重载。以下是您的String类的

std::istream& operator>>(std::istream& is, String& s)
{
    // code for extraction goes here
}

如果您有提取器需要访问的私有成员,则可以将其声明为类的朋友。