0

该程序的重​​点是从文件中读取指令列表。\t在第一次通过时,我只是在他们面前得到最左边的命令(唯一没有 a 的命令)。我已经设法做到了,但是我遇到的问题是,在我测试我的代码以查看是否正确复制了 char 数组时,我的输出左侧出现了非常奇怪的字符.

这是我正在阅读的原始文件:# 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

然而,我收到的奇怪输出是:

D
D
D
DTOP
DTOP
DTOP
DTOP
DTOP
DTOP
DTOP
DTOP
DVAL
D
D

我只是不确定我是如何得到如此奇怪的输出的。这是我的代码:

#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 symTbl [1000][1000];

char line[100], label[9];
char* pch;

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

while (myFile.good())
{
    myFile.getline(line, 100, '\n');

    if (line[0] == '#')
    {
        continue;
    }


    if ( line[0] != '\t' && line[0]!=' ')
    {
        pch = strtok(line-1," \t\n");
        strcpy(label,pch);
    }

    cout << label<< endl;

        }



return 0;
}

任何帮助将不胜感激。

4

2 回答 2

0

也许您错过了 的else案例if ( line[0] != '\t' && line[0]!=' '),您需要label在打印之前给出一些价值。

于 2012-09-15T09:12:44.520 回答
0

一个主要问题是您没有初始化label数组,因此它可以包含任何随机数据,然后您将其打印出来。另一个问题是您每次迭代都会打印标签,即使您没有获得新标签。

您的代码还有一些其他问题,例如不检查是否strtok返回NULL,您应该真正使用while (myFile.getline(...))而不是while (myFile.good()).

找出主要问题的原因的最佳方法是在调试器中运行程序,并逐行执行。然后你会看到发生了什么,并且可以检查变量以查看它们的内容是否是它应该是的。哦,停止使用字符数组,std::string尽可能多地使用。

于 2012-09-15T09:29:21.960 回答