首页 > 解决方案 > 在 C++ 中查找字符并执行与该字符相关的命令

问题描述

我在这里有以下代码,基本上我输入了一个文件,该文件上有某些命令。例如,该文件可能如下所示:

s
u 1
u 2
u 3
o 
o
o

这些字符中的每一个都有一个关联的命令。

我在下面编写了以下代码,但不确定如何处理uando命令。

void Stack::solution(const char *input_path, const char *output_path) {

    string line; 
    ifstream myfile (input_path);
    if (myfile.is_open()) {
        while (myfile.good()) {
            getline (myfile,line);
            while (!myfile.eof()) {
                if (line.find("c") == line.npos) {
                    cout << line << endl;
                }
                if (line.find("s")) {
                    Stack();
                }
                if (line.find("u")) {
                    // need to figure out this part
                }
            }
            
        } 
    }
}

预期的输出是:

3
2
1

标签: c++data-structuresstack

解决方案


C++ 标准库有一个std::stack类。我假设Stack是学校作业的自定义课程?

您已经知道如何从输入文件中读取行。您可以使用std::istringstream来解析这些行。

尝试这样的事情:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stack> // <-- remove if you're not allowed to use std::stack
using namespace std;

void Stack::solution(const char *input_path, const char *output_path) {

    ifstream inputFile (input_path);
    ofstream outputFile (output_path);

    if (!inputFile.is_open() || !outputFile.is_open()) {
        return;
    }

    stack<int> stk; // or: Stack stk;
    string line; 

    while (getline (inputFile, line)) {
        istringstream iss (line);
        char cmd;

        if (!(iss >> cmd)) {
            continue;
        }

        switch (cmd) {
            case 's': {
                stk = stack<int>(); // or: stk = Stack();
                // alternatively, if using std::stack:
                // stack<int>().swap(stk);
                break;
            }

            case 'u': {
                int value;
                if (iss >> value) { 
                    stk.push(value);
                }
                break;
            }

            case 'o': {
                if (!stk.empty()) {
                    outputFile << stk.top() << '\n';
                    stk.pop();
                    // or: if your custom Stack has a pop() that returns the popped value:
                    // outputFile << stk.pop() << '\n';
                }
                break;
            }
        }
    }
}

演示


推荐阅读