2012-09-15 24 views
0

该程序的全部内容是从文件中读取指令列表。在第一次通过时,我只是在最左侧获得命令(仅有没有\t的命令)。我设法做到这一点,但我遇到的问题,而我正在测试我的代码,看看我是否已经正确地复制了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; 
} 

任何帮助将不胜感激。

+0

预期产量是多少? –

+0

@JoachimPileborg除了D之外,预期的输出是原始输出中的所有内容。 – cadavid4j

回答

0

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

+0

我不确定它是否与此有关。我得到正确的输出,我只是接收到覆盖它们的奇怪字符。 – cadavid4j

+0

@ cadavid4j:你能提一下_strange characters_吗?还是我想念他们? –

+0

当我从strtok()中的delimeters列表中拿走\ n时,D的确很奇怪,并且换行符显示覆盖了我的输出。 – cadavid4j

0

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

也有一对夫妇的其他问题与您的代码,就像如果strtok回报NULL不检查,你应该真正使用while (myFile.getline(...))代替while (myFile.good())

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

相关问题