Hi, can anyone give an example how to write a function that could work when you'd want to use multiple input files but not write separate functions? I couldn't find anything about this in the tutorials.
#include <fstream>
#include <iostream>
#include <limits>
#include <string>
int openTwoFiles(std::string& filename1, std::string& filename2);
int main()
{
std::string file1 = "myfile1.txt",
file2 = "myfile2.txt";
std::cout << "\nI've just opened (and closed) "
<< openTwoFiles(file1, file2) << " files in one function.\n";
std::cout << "\nPress ENTER to continue...\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return 0;
}
int openTwoFiles(std::string& filename1, std::string& filename2)
{
int opened_file_counter = 0;
std::ifstream file1(filename1);
std::string sentence;
std::getline(file1, sentence);
std::cout << sentence << '\n';
opened_file_counter++;
std::ifstream file2(filename2);
std::getline(file2, sentence);
std::cout << sentence << '\n';
opened_file_counter++;
file1.close();
file2.close();
return opened_file_counter;
}
output:
Beauty will save the world (Fyodor Dostoyevsky).
The best time to plant a tree was twenty years ago. The second best time is now (Iranian proverb).
I've just opened (and closed) 2 files in one function.
Press ENTER to continue...
It's not clear from the OP if he means open two files in the same function as enoizat demonstrated, or if the OP meant to use the same function to process multiple files.