|
|
|
|
|
|
|
//******************************************************************
#include <iostream.h>
void CountChars();
int count; // Supposed to count input lines, but does it?
char ch; // Holds one input character
int main()
{
count = 0;
while (cin)
{
count++;
CountChars();
}
cout < count < lines of input processed. < endl;
return 0;
}
//******************************************************************
void CountChars()
// Counts the number of characters on one input line
// and prints the count
{
count = 0; // Side effect
cin.get(ch);
while (ch != \n)
{
count++; // Side effect
cin.get(ch);
}
cout < count < characters on this line. < endl;
} |
|
|
|
|
|
|
|
|
The Trouble program is supposed to count and print the number of characters on each line of input. After the last line has been processed, it should print the number of lines. Strangely enough, each time the program is run, it reports that the number of lines of input is the same as the number of characters in the last line of input. This is because function CountChars accesses the global variable count and uses it to store the number of characters on each line of input. |
|
|
|
|
|
|
|
|
There is no reason for count to be a global variable. If a local variable count is declared in main and another local variable count is declared in CountChars, the program works correctly. There is no conflict between the |
|
|
|
|
|