我是C++的新手,想要将一个文本文件读入结构体中。这个文本文件的第一行是double类型的数字,之后的每一行都表示礼物名称(愿望)。我创建了一个Wishlist结构体,包含一个double类型的数字和一个愿望向量。所以我做了以下操作:
#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;
}
当我试图构建和运行时,我又赢得了一些错误奖项!第一个错误是这样说的:(in reference to: wish_list.budget<
对于二进制运算符<<,类型'double'和'double'的操作数无效。
这是什么意思?我需要重新定义运算符<<吗?还是可以将double读取为C字符串,然后再将其更改为double?
我该如何处理这个问题?更好的方法是:如何从文件中读取不同类型的数据?因为我还要将文件读入结构体Giftstore中,其中文本文件将在每行包含一个double和一个礼物名。
wish_list.budget = money;
而不是wish_list.budget<<money;
。 - BenjiWiebeWishlist wish_list;
,以便实际拥有一个Wishlist
类型的对象来使用。 - BenjiWiebe