我正在从包含一些看起来像这样的汇编指令的文本文件中读入
[label]操作码[arg1] [,arg2]
现在我只是处于阅读标签的阶段,但是当我从文件中读取并将标签输入到数组中时,我得到一些不应该存在的空行。这是我的代码
#include <string>
#include <iostream>
#include <cstdlib>
#include <string.h>
#include <fstream>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[])
{
// If no extra file is provided then exit the program with error message
if (argc <= 1)
{
cout << "Correct Usage: " << argv[0] << " <Filename>" << endl;
exit (1);
}
// Array to hold the registers and initialize them all to zero
int registers [] = {0,0,0,0,0,0,0,0};
string memory [16000];
string Symtablelab[1000];
int Symtablepos[1000];
string line;
string label;
string opcode;
string arg1;
string arg2;
// Open the file that was input on the command line
ifstream myFile;
myFile.open(argv[1]);
if (!myFile.is_open())
{
cerr << "Cannot open the file." << endl;
}
int counter = 0;
int i = 0;
int j = 0;
while (getline(myFile, line, '\n'))
{
if (line[0] == '#')
{
continue;
}
if (line[0] != '\t' && line[0] != ' ')
{
string delimeters = "\t";
int current;
int next = -1;
current = next + 1;
next = line.find_first_of( delimeters, current);
label = line.substr( current, next - current );
Symtablelab[i] = label;
cout << Symtablelab[i] << endl;
i++;
}
}
return 0;
}
我从这段代码得到的输出是:
blank line
TOP
VAL
TAN
blank line
我应该得到:
TOP
VAL
TAN
以下是我正在阅读的示例文本文件
# Sample Input
LA 1,3
LA 2,1
TOP NOP
ADDR 3,1
ST 3, VAL
CMPR 3,4
JNE TOP
P_INT 1,VAL
P_REGS
HALT
VAL INT 0
TAN LA 2,1
答案 0 :(得分:1)
评论后的空白行和结尾的隐含空白行导致了您的问题。您应该在注释检查后添加一个空白行。
if (line.length == 0) {
continue;
}