2014-11-21 114 views
-1

我有一種感覺,這將是一個非常簡單的問題來回答,但我無法找到這種情況的一個例子。我有一個算法讀入輸入文件並解析每行上的所有字符串。如果第一個字符是0,則將該行上的字符串寫入輸出文件。我已經成功實現了在main()中編程,但是我想將它重寫爲可以從main()調用的函數(Line_Parse)。爲了做到這一點,輸入文件需要在main()中打開並從函數中讀取;但是,由於iostream名稱「inp」是在main()中定義的,因此它在函數中不被識別。現在附上一份函數和主程序的副本,我希望能指導如何將流「inp」傳遞給主程序。在C++函數中,如何從main()中打開的輸入文件讀取?

void Line_Parse(char *&token,int MAX_CHARS_PER_LINE, 
      int MAX_TOKENS_PER_LINE,char DELIMITER); 

int main(int argc, const char * argv[]) { 

    std::string Input_File("Input.txt"); 
    const int MAX_CHARS_PER_LINE = 1200; 
    const int MAX_TOKENS_PER_LINE = 40; 
    const char* const DELIMITER = " "; 

    std::ifstream inp(Input_File, std::ios::in | std::ios::binary); 
    if(!inp) { 
     std::cout << "Cannot Open " << Input_File << std::endl; 
     return 1; // Terminate program 
    } 
    char *token; 
    // read each line of the file 
    while (!inp.eof()) 
    { 
     Line_Parse(token,MAX_CHARS_PER_LINE,MAX_TOKENS_PER_LINE, 
        *DELIMITER); 
    } 
    inp.close(); 
    return 0; 
} 

void Line_Parse(char *&token,int MAX_CHARS_PER_LINE, 
       int MAX_TOKENS_PER_LINE,char DELIMITER) 
{ 
    // read an entire line into memory 
    char buf[MAX_CHARS_PER_LINE]; 
    inp.getline(buf, MAX_CHARS_PER_LINE); 

    // parse the line into blank-delimited tokens 
    int n = 0; // a for-loop index 

    // array to store memory addresses of the tokens in buf 
    *&token[MAX_TOKENS_PER_LINE] = {}; // initialize to 0 

    // parse the line 
    token[0] = *strtok(buf, &DELIMITER); // first token 
    if (token[0]) // zero if line is blank 
    { 
     for (n = 1; n < MAX_TOKENS_PER_LINE; n++) 
     { 
      token[n] = *strtok(0, &DELIMITER); // subsequent tokens 
      if (!token[n]) break; // no more tokens 
     } 
    } 
} 
+1

將它作爲參數傳遞給函數。 – Barmar 2014-11-21 01:35:45

+1

'while(!inp.eof())'如果你打開一個空文件,這不起作用。不需要任意大小的字符緩衝區。使用字符串,他們將接受任何大小的行。 – 2014-11-21 01:37:39

+0

http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – 2014-11-21 01:57:31

回答

1

更改接受inp爲參數的函數:

void Line_Parse(char *&token,int MAX_CHARS_PER_LINE, 
       int MAX_TOKENS_PER_LINE,char DELIMITER, std::ifstream inp) 

然後稱其爲:

Line_Parse(token, MAX_CHARS_PER_LINE, MAX_TOKENS_PER_LINE, *DELIMITER, inp); 
+0

當我實現這種方法時,程序編譯失敗。我收到錯誤消息「調用std :: if流的隱式刪除拷貝構造函數」,在函數調用中引用inp。如何在函數頭中引用std :: if stream inp沒有問題,但它不喜歡在函數調用中如何引用它。 – Jon 2014-11-21 02:30:53

+0

我能夠通過調用函數Line_Parse(inp,out)和將原型寫爲void Line_Parse(std :: if stream&inp,std :: stream&out)來解決問題。 – Jon 2014-11-21 14:28:00

2

其實Input_File是處理你的input.txt文件,以便使用這個處理函數在你的Line_Parse函數中需要把它作爲參數傳遞給函數。

void Line_Parse(char *&token,int MAX_CHARS_PER_LINE,int MAX_TOKENS_PER_LINE, 
             char DELIMITER, std::ifstream & inp); 

你會這樣稱呼它。

Line_Parse(token, MAX_CHARS_PER_LINE, MAX_TOKENS_PER_LINE, *DELIMITER, Input_File); 
+0

不幸的是,這也不起作用。如果我將句柄作爲inp傳遞,它會識別函數名稱,如果我嘗試將它作爲Input_File傳遞,它將不再識別函數名稱。 – Jon 2014-11-21 02:42:18