我有一種感覺,這將是一個非常簡單的問題來回答,但我無法找到這種情況的一個例子。我有一個算法讀入輸入文件並解析每行上的所有字符串。如果第一個字符是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