gpt4 book ai didi

c++ - 从 vector 文件中读取数据

转载 作者:行者123 更新时间:2023-11-30 01:04:19 29 4
gpt4 key购买 nike

我的任务是将文件中的数据读入 vector 中:

21000 Landhau Nolte brown
19000 Modern_fit Hoeffner magnolie
14700 Pure_Style Wellmann black

这是我的尝试,但推回无效。我已经在 Stack Overflow 上查看了一些示例,但不知何故它不起作用。

函数.h:

#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;

struct Kitchen {
double price;
string name;
string manufacturer;
string color;
};

main.cpp:

#include "functions.h"

int main(){

vector<Kitchen> Kitchens;

fstream myFile;
myFile.open("kitchen.txt", ios::in);
if (myFile.is_open()) {
while (!myFile.eof()) {
double price;
string name;
string manufacturer;
string color;
myFile >> price >> name >> manufacturer >> color;
Kitchens.push_back(price, name, manufacturer, color);

}

myFile.close();
}
else cout << "not opened." << endl;

system("PAUSE");
return EXIT_SUCCESS;
}

我做错了什么?

最佳答案

structure 是一种聚合类型,但是为了将 struct 对象推送到 struct 的 vector 中,您必须创建一个,即使它可能是临时的:

#include <iostream>
#include <vector>
using namespace std;
struct Kitchen {
double price;
string name;
string manufacturer;
string color;
};
int main() {
std::vector<Kitchen> kt;
kt.push_back(Kitchen{21000,"Landhau","Nolte","brown"});

return 0;
}

同样,只需稍加修改并在 Kitchen 结构中使用参数化构造函数,您就可以避免 push_back 的内部复制/移动操作并直接使用 emplace_back。

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct Kitchen {
double price;
string name;
string manufacturer;
string color;
Kitchen(double p,
const string& n,
const string &m,
const string &c):price(p),name(n),manufacturer(m),color(c) {}
};
int main(){

vector<Kitchen> Kitchens;

fstream myFile;
myFile.open("kitchen.txt", ios::in);
if (myFile.is_open()) {
while (!myFile.eof()) {
double price;
string name;
string manufacturer;
string color;
myFile >> price >> name >> manufacturer >> color;
Kitchens.emplace_back(price, name, manufacturer, color);

}

myFile.close();
}
else cout << "not opened." << endl;

system("PAUSE");
return EXIT_SUCCESS;
}

关于c++ - 从 vector 文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50344072/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com