2014-02-22 31 views
0

我已經把我的代碼的簡化版本放在這裏。我想要做的是從輸入文件中讀取每一行並將其存儲在「fifo」類中。但是在每個商店之前,我嘗試打印先前的fifo值(這是爲了調試)。我所看到的是,即使在我調用fifo.add函數之前,以前的值也會被覆蓋。 getline函數本身自己覆蓋fifo。有人能告訴我這裏發生了什麼嗎?將外部變量傳遞給一個類C++

//fifo.h 

#ifndef FIFO_H_ 
#define FIFO_H_ 

class fifo { 
     private: 
       char* instr_arr; 
       int head; 
       int tail; 
     public: 
       fifo(); 
       fifo(int,int); 
       void add(char*); 
       void print_instruction(void); 
}; 

#endif 

//fifo.cpp 

#include "fifo.h" 
#include <iostream> 
//using namespace std; 

fifo::fifo() { 
     head = 0; 
     tail = 0; 
     instr_arr = "NULL"; 
} 

fifo::fifo(int h, int t) { 
     head = h; 
     tail = t; 
} 

void fifo::add (char *instr) { 
     instr_arr = instr; 
} 

void fifo::print_instruction (void) { 
     std::cout << instr_arr << std::endl; 
} 

//code.cpp 

#include <iostream> 
using namespace std; 
#include <fstream> 
using namespace std; 
#include "fifo.h" 

#define MAX_CHARS_INLINE 250 

int main (int argc, char *argv[]) { 
     char buf[MAX_CHARS_INLINE];  //Character buffer for storing line 
     fifo instruction_fifo;   //FIFO which stores 5 most recent instructions 

     const char *filename = argv[1]; 
     ifstream fin; 
     fin.open(filename); 

     while(!fin.eof()) { 
       std::cout << buf << std::endl; 
       fin.getline(buf, MAX_CHARS_INLINE); 
       instruction_fifo.print_instruction(); //This instruction prints the line which was read from getline above!! Why?? 
       instruction_fifo.add(buf); 
       } 
     return 0; 
} 
+1

我建議使用'std :: string',而不是'char *'。而不是使用'while(!eof())' – chris

+0

如果這不是一個練習,STL是你的朋友 –

回答

1

您還沒有實際存儲數據的FIFO(或在由FIFO管理的存儲器塊),只有指針(其指向buf)。

當您打印instr_arr時,您基本上正在打印buf,因爲instr_arr指向buf