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

标签 c++ vector fstream

我的任务是将文件中的数据读入 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/

相关文章:

c++ - 为什么这个 fstream 命令不起作用?

c++ - 使用 ofstream 保存文本文件的困难

c++ - 为什么使用具有某些类型特征的模板类型会导致模板推导失败

c++ - 返回 C++ 迭代器引用

c++ - 比较字符串不区分大小写的简单方法是什么?

matlab - 在 MATLAB 中存储向量的唯一字符串/元素的索引

c++ - C++ 中的简单文本文件加密

c++ - OpenCV:HOGDescriptor.compute

c++ - 使用对象表达式在构造函数中调用虚函数

c++ - union 类型的模板特化