我正在为学校的班级开发一个项目。这是一个简单的堆栈和队列实现。然而,作为项目的一部分,我们需要从文件中读取操作码。将文件输入作为C++中的操作码读取
append 10
serve
append 20
append 30
serve
push 10
push 50
push 20
push 20
pop
我的问题是,当我在文件中通过标准fstream的阅读似乎挑选了一些很怪的格式或什么的,并不会匹配比较检查:操作码如下格式化。
我在想我在做什么错,如何解决它,以及是否有更好的方法来操纵未来的操作码。就像这样,if-else语句总是转到if。非常需要这种工作。
#include "StackAndQueue.h"
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main(){
Stack leStack;
Queue leQueue;
//Read in the datafile.
cout << "Reading default file: p2datafile.txt";
fstream data("p2datafile.txt");
while (data.fail()){
cout << " failed." << endl;
data.close();
cout << "Please enter path to datafile: ";
string filename;
cin >> filename;
data.open(filename.c_str());
}
cout << endl << "Sucess!" << endl;
//Loop through all the commands in the file
while(!data.eof()){
// Determine what kind of command is running
// and if parsing will be needed.
string opcode;
getline(data,opcode,' ');
if (opcode == "pop"){
cout << "popping!" << endl;
leStack.pop();
}
else if (opcode == "serve"){
cout << "serving" << endl;
leQueue.serve();
}
else if (opcode == "push"){
cout << "pushing";
}
else{
cout << "else!" << endl;
}
}
data.close();
system("pause");
return 0;
}
我很抱歉如果代码难以阅读,以及它的一般半成品性质。我对此仍然很陌生。
能否请您附上了错误的输出你? (顺便说一句,摆脱那个丑陋的系统(“暂停”);) – 2010-09-21 09:41:38
标准流操作符会自动在空白区域中断。但是你的getline()只在空间上(而不是选项卡)中断,所以要小心输入文件不包含制表符(或使用操作符>>)。 – 2010-09-21 10:48:00
另外你对eof()的测试不正确。在读过文件结尾之前,eof标志没有设置为true。所以,如果你阅读整个文件(没有任何遗漏),它仍然是错误的,并进入循环。下一次调用getline()会失败,并使opcodde处于不确定状态(可能是“”,从而导致打印“else!”)。 – 2010-09-21 10:50:29