#include <iostream>
#include <map>
#include <fstream>
struct huffman_node {
int priority;
char letter = 0; // Use null char for internal nodes,
// and the actual char for leaf nodes
huffman_node* left = nullptr, * right = nullptr;
};
void freq_dist_from_file(std::map<char, int>&, std::ifstream&)
{
std::ifstream my_file("text.txt");
if (!my_file.is_open())
throw std::runtime_error("Can not open file.");
std::map<char, int> freq_dist;
freq_dist_from_file(freq_dist, my_file);
}
int main()
{
system("pause");
}
What should I write on main to check that my text.txt file open suceessful or not?
In my opinion, it would be better, opening the file in main() and testing it there for successfully opening. Also, I think it isn't a good idea calling your freq_dist_from_file() in a recursive manner if you don't want to risk a stack overflow.
Are you sure that your professor told you, recursively invoking the function? I could bet, your prof was providing this code for analyzing and recognizing what's wrong with.
But anyway, a possibility to check if your file would be correctly opened in main would be, catching the exception.
void freq_dist_from_file(std::map<char, int>&, std::ifstream&)
Seems more that you have to create the map and the stream in main and pass it to void freq_dist_from_file.
To do it you need to give the parameters a name.
What is the huffman_node needed for if you use a map?
Can you please give me a full code?
We are not a code writing service.
What would you learn from it?
freq_dist_from_file() is recursive, but you don't pass thru the map, you create a local one and trash the results after each return.
You shouldn't be handling the exception in freq_dist_from_file(). That's the magic of exceptions, you throw the error in one function and you can catch them anywhere down the call stack. In this case, main() should catch error, freq_dist_from_file() should just throw it.
Finally, you're not actually doing anything useful, but if the exercise is to learn about exceptions, that's ok.