从文本文件中读取已创建的结构类型时遇到问题
Having trouble reading in created struct types from a text file
我正在尝试从.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;
此外,正在读取的信息只是文本。如有任何帮助或意见,我们将不胜感激。
两个变量artist
和title
是指针,而不是对象。因此,如果你做了以下事情,你就不会看到同样的行为:
String artist;
input_file >> artist;
当然,假设您有适当的operator>>()
过载(我稍后会对此进行解释(。
当您尝试读取指针时,会出现错误,因为编译器找不到流提取运算符(operator>>()
(的重载,该重载将指向String
的指针作为右手参数。您之所以在底部看到"cannot convert 'title' to type 'signed char*'
,是因为编译器列出了所有候选重载以及它们在尝试将artist
或title
转换为右侧参数时发出的相应错误。
如果需要使用指针,则必须将其初始化为有效对象。您必须取消引用指针以获得对其所指向对象的引用,这样流就可以将数据读取到其中:
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
}
如果您有提取器需要访问的私有成员,则可以将其声明为类的朋友。
- 没有类型结构绑定不起作用?
- 如何使用指针连接两种不同的节点类型(结构)?
- 无法汇总初始化类型结构的变量,其中包含在类模板中的位字段成员
- 您如何声明类型结构的堆栈?在C 中
- 访问指向相同类型结构的指针
- 静态数据类型(结构)的组织
- 创建类型结构的指针阵列
- 处理类型结构数组
- 嵌入式 C++:在 C++ 中初始化易失性类型结构
- Mac OSX的c++中的变量类型结构(oaidl.h)
- 嵌套类型:结构与类
- 如何在 python 中实现 c++ 类型结构
- 如何使用类型结构定义双端队列(双面队列)
- 删除类型结构的元素形式向量
- 从类型结构的向量中删除元素
- 在c#、c++和java中创建python弱类型结构的强类型版本
- 从较大的数据类型(结构)转换为较小的数据类型
- 使用QGLShaderProgram从Qt传递自定义类型(结构体)统一到GLSL
- 如何:公开c++数据结构/类型(结构体,枚举)供c#使用
- 按值将类型结构传递给函数,错误:声明"average"中的两个或多个数据类型!!-