2014-02-22 29 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