Hello, I having some trouble with my countCharacters() function. when i run the program everything works as intended but when I run the function twice as seen below, it adds both functions together when I want it to display each total separately.
The countCharacters() function is suppose to open the txt file and count the amount of characters within.
for ex, the groceries.txt has 344 characters, and names.txt has 75. when i run the program the first output is,
# of characters in the file : 344
when the program hits the second function its outputs,
# of characters in the file : 419
when it should be 75.
int main()
{
int char_count{};
countCharacters("groceries.txt", char_count);
cout << "# of characters in the file : " << char_count << endl;
countCharacters("names.txt", char_count);
cout << "# of characters in the file : " << char_count << endl;
}
Lines 5 - 8 are not really helping the compiler that much to make any difference. And you should stop writing the code for the compiler and start writing code that you and others can read.
1 2 3 4 5 6 7 8 9 10 11
int main()
{
int char_count{};
countCharacters("groceries.txt", char_count);
cout << "# of characters in the file : " << char_count << endl;
countCharacters("names.txt", char_count);
cout << "# of characters in the file : " << char_count << endl;
}
Just 1 blank line makes the problem easy to see.
Your code works, but it could use some other changes.
ch_cnt needs to be set to 0 at the beginning of the function as it's passed by ref - so has the initial value in the function the same as the previous value.
Also, the count function can be much simplified. isalpha() returns true(1) if the specified char is a letter (upper or lower case) or false (0) otherwise. So ch_cnt is only incremented by 1 if ch is either a letter or a space. Noe that is also isspace(). But this doesn't do quite what might be expected. It returns true if the specified cha is a white-space char (' ', '\t', '\n) and not just space char.