我有一种感觉,这将是一个非常简单的问题来回答,但我无法找到这种情况的一个例子。我有一个算法读入输入文件并解析每行上的所有字符串。如果第一个字符是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
}
}
}
将它作为参数传递给函数。 – Barmar 2014-11-21 01:35:45
'while(!inp.eof())'如果你打开一个空文件,这不起作用。不需要任意大小的字符缓冲区。使用字符串,他们将接受任何大小的行。 – 2014-11-21 01:37:39
http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – 2014-11-21 01:57:31