gpt4 book ai didi

c++ - 在 C++ 中读取文件输入作为操作码

转载 作者:行者123 更新时间:2023-11-28 03:55:37 25 4
gpt4 key购买 nike

我正在为学校的一个类(class)做一个项目。它是栈和队列的简单实现。然而,作为项目的一部分,我们需要从文件中读取操作码。操作码格式如下:

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;
}

如果代码难以阅读,以及它一般的半成品性质,我深表歉意。我对此还是很陌生。

最佳答案

以这种方式使用的

getline 仅将 ' ' 视为分隔符,因此它不会在换行符处停止;此外,您没有提取参数(当操作码有任何参数时),因此在下一次迭代时它将作为操作码读取(粘贴在真实操作码的前面)。

在我看来,您只需使用普通的 operator>> 即可。它在任何空白处正确停止(这是你想要做的)并正确支持 C++ 字符串。重要的是要记住在需要时也提取参数(同样,使用 operator>>),在错误数字的情况下观察 istream::fail() 错误格式化。您甚至可能希望在出现这些错误时出现流上升异常(这样它们就不会被忽视)。

try
{
string opcode;
data.exceptions(ios::failbit);
//Loop through all the commands in the file
while(data>>opcode){
// Determine what kind of command is running
// and if parsing will be needed.

int argument;

if (opcode == "pop"){
cout << "popping!" << endl;
leStack.pop();
}
else if (opcode == "serve"){
cout << "serving" << endl;
leQueue.serve();
}
else if (opcode == "push"){
cout << "pushing";
data >> argument;
}
else if (opcode == "append"){
cout << "appending";
data >> argument;
}
else{
cout << "else!" << endl;
}
}
data.close();
}
catch(const ios::failure & ex)
{
if(!data.eof())
cout<<"IO error"<<endl;
}

关于c++ - 在 C++ 中读取文件输入作为操作码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3758956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com