【问题标题】:Reading file into structure (c++) [closed]将文件读入结构(C++)[关闭]
【发布时间】:2012-12-07 01:32:40
【问题描述】:

我对 C++ 非常陌生,我想将一个文本文件读入一个结构中。文本文件的第一行有一个 double,之后的行作为礼物名称(愿望)存在。我创建了一个结构体 Wishlist,它以双精度和愿望向量的形式存在。所以我做了以下事情:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

struct Gift
{
    double price;
    string name;
};

typedef vector<Gift> Giftstore;
typedef vector<string> Wishes;


int size(Giftstore& g) {return static_cast<int>(g.size());}

int size(Wishes& w) {return static_cast<int>(w.size());}


struct Wishlist
{
    double budget;
    Wishes wishes;
};


void reading_wishlist(ifstream& file, Wishlist& wish_list)
{
    if (file)
    {
        double money;

        file>>money;
        wish_list.budget<<money;
    }

    while(file)
    {
        string name;
        getline(file, name)
        wish_list.wishes.push_back(name);
    }

    file.close();
};


void print(Wishlist wish_list)
{
    cout<<"Budget: "<<wish_list.budget<<endl;
    cout<<"Wishes: "<<endl;

    for(int i=0; i<size(wish_list.wishes()); i++)
    {
        cout<<wish_list.wishes[i]<<endl;
    }
};

int main () {

  ifstream file;
  string filename;
  cout<<"Give a wishlist file: ";
  cin>>filename;

  file.open(filename)
  reading_wishlist(filename, wish_list);
  print(wish_list)

  return 0;
}

当然,在尝试构建和运行它时,我又赢得了一些错误奖励!第一个是说:(参考:wish_list.budget

'double' 和 'double' 类型的无效操作数到二元运算符

这是什么意思?我是否必须重新定义运算符

解决这个问题的最佳方法是什么?更好:如何从文件中读取不同的类型?由于我还必须将文件读入结构,Giftstore,其中文本文件将由每行的双精度名称和礼物名称组成。

【问题讨论】:

  • 请发布完整的错误信息。您缺少一些关键信息,例如发生错误的文件名和行号。还请指出哪行代码给出了错误。
  • 看起来不错,您错过了一些行尾分号。 43、69、71 行
  • “这是什么意思?” - 这意味着您输入的内容没有意义。你想做什么?
  • 第 37 行;你应该做wish_list.budget = money; 而不是wish_list.budget&lt;&lt;money;
  • 第 68 行;应该是 Wishlist wish_list; 才能实际使用 Wishlist 类型的对象

标签: c++ data-structures vector


【解决方案1】:

错误来自reading_wishlist函数中的这一行

wish_list.budget&lt;&lt;money;

您不能将 &lt;&lt; 运算符与作为左侧的 double 一起使用(此处为 WishList::budget)。
你是说

wish_list.budget = money;

【讨论】:

  • 不客气!如果它解决了您的所有问题,您可以将其标记为答案。此外,如果您将 void reading_wishlist 重命名为 ifstream&amp; operator&gt;&gt; 并返回 file 而不是关闭它,您可以根据需要编写 file&gt;&gt;wish_list
  • 非常感谢您的帮助!只有放入结构中的双精度为 1.6965e+260,在文本文件中为 50.00,向量中没有任何内容:-S
  • @Lola 你的意思是如果你把它改成operator&gt;&gt;?
  • 等一下……它甚至对不存在的文件也这样做……
  • 对不存在的文件有意义。您得到的是未初始化的双精度和向量-您永远不会输入if(file)while(file) 顺便说一句,您可能还想在cin 之后检查file 的状态,因为您将获得的最后一件事cin 将是文件结束
猜你喜欢
  • 2021-02-13
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 2013-12-16
  • 1970-01-01
相关资源
最近更新 更多