c++ - 在 C++ 中查找字符并执行与该字符相关的命令
问题描述
我在这里有以下代码,基本上我输入了一个文件,该文件上有某些命令。例如,该文件可能如下所示:
s
u 1
u 2
u 3
o
o
o
这些字符中的每一个都有一个关联的命令。
S
: 创建一个空栈。u
: 将一个值压入堆栈。o
从堆栈中弹出一个值并将其写入输出文件。
我在下面编写了以下代码,但不确定如何处理u
ando
命令。
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++ 标准库有一个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;
}
}
}
}
推荐阅读
- .net - 如何为托管 COM 组件服务器进行绑定重定向\编组
- mysql - 使用 sum(cloumnC) 选择不同的 columnA 和 columnB
- python - Python:如果行中只有 1 个单词,则替换数据框/列中的字符串
- python - Django表单DateField初始值未更新
- java - Java:打印格式,一行有两个数组,长度不同
- gradle - 并行 Gradle 任务同时运行
- javascript - 替换行索引的算法
- c# - Unity,MoveTowards 工作很奇怪
- python-3.x - 影响图形的 Tkinker 光标
- windows - 在 windows 上使用 --coverage 使用 clang 构建应用程序