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

如何逐行搜索文本文件并按类别创建对应游戏对象?

Solution for Parsing Game Categories and Creating Objects

Hey there! Let's break down how to solve this problem. The key challenge here is correctly splitting each line into the category and the full game name (even when the name has spaces), then instantiating the right object type for each entry.

First, make sure you have your base Game class and derived classes (MMO, Strategy, Arcade, AR) defined with a constructor that accepts a name and description. For example:

#include <string>
class Game {
protected:
    std::string name;
    std::string description;
public:
    Game(std::string n, std::string desc) : name(n), description(desc) {}
    // Virtual destructor is critical for polymorphic cleanup
    virtual ~Game() = default;
};

class MMO : public Game {
public:
    MMO(std::string n, std::string desc) : Game(n, desc) {}
};

// Repeat similar definitions for Strategy, Arcade, AR classes

Now, let's modify your main function to handle the file parsing correctly:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm> // For sort()

// Include your Game and derived class definitions here

int main() {
    std::ifstream inFile("Games.txt");
    // Check if file opened successfully
    if (!inFile) {
        std::cerr << "Unable to open file" << std::endl;
        return 1;
    }

    std::vector<Game*> games;
    std::string line;

    // Read each line of the file
    while (std::getline(inFile, line)) {
        // Find the first space to split category and game name
        size_t splitPosition = line.find(' ');
        // Skip lines that don't follow the "Category GameName" format
        if (splitPosition == std::string::npos) {
            std::cerr << "Skipping invalid line: " << line << std::endl;
            continue;
        }

        std::string category = line.substr(0, splitPosition);
        // Extract everything after the first space as the full game name
        std::string gameName = line.substr(splitPosition + 1);
        // You can set a default description or leave it empty
        std::string description = "";

        // Create the appropriate object based on category
        if (category == "MMO") {
            games.push_back(new MMO(gameName, description));
        } else if (category == "Strategy") {
            games.push_back(new Strategy(gameName, description));
        } else if (category == "Arcade") {
            games.push_back(new Arcade(gameName, description));
        } else if (category == "AR") {
            games.push_back(new AR(gameName, description));
        } else {
            std::cerr << "Unknown category: " << category << " for game: " << gameName << std::endl;
        }
    }

    // Now you can use your games vector (e.g., sort it, iterate through it)
    // std::sort(games.begin(), games.end(), yourComparisonFunction);

    // Clean up memory to avoid leaks
    for (Game* game : games) {
        delete game;
    }
    games.clear();

    inFile.close();
    return 0;
}

Key Points Explained:

  • Reading Entire Lines: We use std::getline instead of the >> operator because >> stops at the first space. This lets us capture full game names with spaces (like "League Of Legends").
  • Splitting the Line: line.find(' ') locates the first space in the line. We use substr to split the string into the category (before the space) and the full game name (after the space).
  • Object Creation: We check the category string and instantiate the corresponding derived class object, then add it to our vector<Game*>.
  • Memory Management: Since we're using raw pointers, we loop through the vector at the end to delete each object and avoid memory leaks. For a safer approach, you could use std::vector<std::unique_ptr<Game>> to handle memory automatically.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 10:42:43