【问题标题】:Having trouble reading in created struct types from a text file从文本文件中读取创建的结构类型时遇到问题
【发布时间】:2014-04-30 19:56:33
【问题描述】:

我正在尝试从 .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;

读入的信息也只是文本。任何帮助或输入将不胜感激,谢谢。

【问题讨论】:

  • 呃,为什么有这么多不必要的指针......
  • @awesomeyi 这是我对 C++ 类的介绍的作业,目的是让我们习惯于使用不舒适的指针量哈哈
  • const char* text; 对于这样的String struct :-/ ... 不会很有用
  • 将数据读入 指向String 对象的指针 对我来说似乎不是很有希望。我会尝试读入String 对象...
  • @CiaPan 我试着做 input_file >> artist->text;相反,它仍然没有工作:/

标签: c++ struct ifstream


【解决方案1】:

artisttitle 这两个变量是指针,而不是对象。因此,如果您执行以下操作,您不会看到相同的行为:

String artist;
input_file >> artist;

当然假设您有一个适当的 operator>>() 重载(我会稍微解释一下)。

当您尝试读入指针时,您会遇到错误,因为编译器找不到将指向 String 的指针作为右手参数的流提取运算符 (operator>>()) 的重载。您在底部看到"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&lt;&gt; 这是一个新的 (C++11) 对象,您可以使用 std::shared_ptr&lt;&gt;


在将流 I/O 语义合并到用户定义的类中时,通常会提供流运算符的重载,随后将数据提取到类的数据成员中。它允许语法:

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

从您向我们展示的内容来看,我认为您没有为 input 流对象提供重载。这是您的String 课程的样子:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多