2014-11-21 118 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