从.txt文件中读取c++命令



我想创建一个小计算器;但是我不知道如何去创造。

我的问题是,我有一个输入文件(.txt)的代码:

acc + 40

-14年acc

nop + 386jmp + 262

acc 4

nop + 25

…"acc"将数字添加到变量

"jmp"是跳转到行(jmp +500跳转到500行)

"nop"不要做任何事

和这里是我的代码,但不工作(acc是好的,但JMP不是)

ifstream file("my.txt");
string cmd;
int num;
int var= 0;
int i = 0;
if(file.is_open())
{
while (file >> cmd >> num)
{
cout << "Var" << var<< endl;
cout << "Command: " << cmd << "   Number: " << num<< " ----" << i <<" //  Var: " << var<< endl;
++i;
if(cmd == "acc")
{
var= var+ num;
}
if(cmd == "jmp")
{
;
}
}
file.close();
}else {
cout << "error"<<  endl;
cin.get();
}

这是一个示例代码。我希望这里一切都井然有序。我是按某个程序员说的做的。使用vector,将所有行读入其中,然后迭代。

#include <fstream>
#include <iostream>
#include <string> //addition
#include <vector> //addition
using namespace std;
int main() {
ifstream file("my.txt");
string cmd;
int num;
int var= 0;
int i = 0;

string my_string;//addition
vector<int> numbers;//addition
vector<string> commands;//addition
if(file.is_open())
{
/*this while function reads every line of the file and writes command to the vector of strings named "commands" and the number to the vector of integers named "numbers".*/
while (getline(file, my_string))//while you can read line from "file", read it and put in into string called "my_string".
{
cmd = my_string;
cmd.resize(3);//leaves only first three characters of the string.
commands.push_back(cmd);//adds this "cmd" string to vector "commands"  

my_string.erase(0,4);//erases characters from 0 to 4, inclusive, from the string "my_string". So erases first 4 characters, so our command and the space after.
numbers.push_back(stoi(my_string));//adds my_string, converted to int, to vector "numbers". Stoi() converts string to int.
++i;
}

for(i = 0; i < commands.size(); i++)
{                          
cout << "Var " << var << endl;
if(commands[i] == "acc")
{
//remember about "+=", it's quicker this way :)
var += numbers[i];
}
cout << "Command: " << commands[i] << "   Number: " << numbers[i] << " ----" << i <<" //  Var: " << var << endl;
if(commands[i] == "jmp")
{
i+= numbers[i];
}

}
file.close();
}else {
cout << "error"<<  endl;
cin.get();
}
}

对于任何格式问题提前表示抱歉。我对stackoverflow的第一个答案…

最新更新