You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++读取文件数据到vector失败求助:push_back无法正常工作

问题分析与修复方案

我一眼就看到了你代码里的两个关键问题,这也是新手常犯的典型错误,咱们一步步来修正:

1. push_back 调用方式错误

vector::push_back() 方法需要接收一个**Kitchen类型的对象**作为参数,但你直接把四个零散的成员变量传进去了,编译器根本不知道怎么把这四个值转换成Kitchen对象。

解决方法有两种,选哪种都可以:

  • 给Kitchen结构体添加自定义构造函数,方便直接用参数创建对象
  • 使用C++11及以上支持的聚合初始化,直接生成临时Kitchen对象

2. 循环条件用eof()的陷阱

用while (!myFile.eof())作为循环条件会导致最后一次读取重复数据——因为eof()标志是在读取失败后才会被设置的,当你读到文件末尾时,循环会多执行一次,把之前的变量值再重复push一遍。正确的做法是把读取操作直接放在循环条件里,当读取失败时自动退出循环。


修复后的完整代码

方案一:给结构体添加构造函数(更直观)

修改functions.h:

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

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

    // 添加自定义构造函数,用参数直接初始化成员变量
    Kitchen(double p, string n, string m, string c)
        : price(p), name(n), manufacturer(m), color(c) {}
};

修改main.cpp:

#include "functions.h"

int main(){
    vector<Kitchen> Kitchens;
    fstream myFile;
    myFile.open("kitchen.txt", ios::in);

    if (myFile.is_open()) {
        double price;
        string name;
        string manufacturer;
        string color;
        // 把读取操作放在循环条件里,读取失败自动退出
        while (myFile >> price >> name >> manufacturer >> color) {
            // 用构造函数创建Kitchen对象并推入vector
            Kitchens.push_back(Kitchen(price, name, manufacturer, color));
        }
        myFile.close();
    } else {
        cout << "not opened." << endl;
    }

    system("PAUSE");
    return EXIT_SUCCESS;
}

方案二:用聚合初始化(无需修改头文件)

如果不想改动functions.h,可以直接用C++的聚合初始化语法,更简洁:

#include "functions.h"

int main(){
    vector<Kitchen> Kitchens;
    fstream myFile;
    myFile.open("kitchen.txt", ios::in);

    if (myFile.is_open()) {
        double price;
        string name;
        string manufacturer;
        string color;
        while (myFile >> price >> name >> manufacturer >> color) {
            // 直接用花括号初始化临时Kitchen对象
            Kitchens.push_back({price, name, manufacturer, color});
        }
        myFile.close();
    } else {
        cout << "not opened." << endl;
    }

    system("PAUSE");
    return EXIT_SUCCESS;
}

最后还要确认你的kitchen.txt文件格式是否正确:每一组厨房数据都是价格 名称 厂商 颜色的顺序,用空格分隔,这样流读取才能正确分组。

内容的提问来源于stack exchange,提问作者mooncrater

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:52:23