2012-09-15 23 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

相關問題