Code Review:
You open the input file in main
and open it again in your count_word
function. You may get errors from the operating system stating that the file is already open.
A good idea is to close a file before opening it again, or pass the file pointer to the function. You could make the file pointer a global variable, but global variables are evil.
Variable names. If you have to explain the variable’s purpose in a comment, you have named it poorly. Don’t worry about the length of variable names because the length does not affect performance and is negligible in the build time.
The proper method to read until EOF is:
while ( infile >> ws)
BTW, the variable ws
is not defined globally or in the count_word
function. The compiler should issue an error message for that.
Words can be input by using a std::string
type variable:
std::string word;
//...
infile >> word; // Read a word.
Prefer not to use the getc
method unless your application must read a single character at a time.
Use std::string::length
to determine the number of characters in a word.
const unsigned word_length = word.length();
if (word_length == 1)
{
++words_of_length_1;
}
Pass by reference for large variables or if the function will modify the variable. Prefer to pass by copy for small variables and constant reference for larger variables.
Your output_table
function does not modify its variables, and the variables are small, so pass by copy:
void output_table(int x, int y, int z, int l) {
solved How to write this code in simple way?