使用 find_first_of() 和 substr() 分隔字符串,但我得到的输出不正确

Using find_first_of() and substr() to seperate a string but I'm getting incorrect output

本文关键字:不正确 输出 分隔 first find of 使用 substr 字符串      更新时间:2023-10-16

我正在从一个文本文件中读入,其中包含一些看起来像这样的汇编指令

[标签] 操作码 [参数 1] [,参数2]

现在我只处于读取标签的阶段,但是当我从文件中读取并将标签输入数组时,我得到了一些不应该存在的空白行。这是我的代码

#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
注释

后面的空行和末尾的隐式空行会导致您的问题。您应该在注释检查空白行之后添加检查。

if (line.length == 0) {
  continue;
}