Saturday, May 22, 2010

Need Help Debugging C++ program?

This purpose of this program is to count the number of characters in a series of text files. The first text file it counts the numbers. But when it gets to the second file it stops counting them So what happends it that it display


int main()


{





int letter1=0;


int letter2=0;


int letter3=0;


char ch;


char ch2;








ifstream input;





input.open("Chapter1.txt");


if (input.fail( ))


{


cout %26lt;%26lt; "Input file opening failed.\n";


return 1;


}





while(input%26gt;%26gt; ch)


{


if (isalnum(ch))//average = (letters);


letter1++;


}





cout %26lt;%26lt; "There are " %26lt;%26lt; letter1 %26lt;%26lt; " letters\n"; //cout %26lt;%26lt; "There average is " %26lt;%26lt; average %26lt;%26lt; " letters per word\n"


input.close();





input.open("Chapter2.txt");


while(input%26gt;%26gt;ch2)


{


if (isalnum(ch2))//average = (letters);


letter2++;


}


cout %26lt;%26lt; "There are " %26lt;%26lt; letter2 %26lt;%26lt; " letters\n"; //cout %26lt;%26lt; "There average is " %26lt;%26lt; average %26lt;%26lt; " letters per word\n"

Need Help Debugging C++ program?
Are you sure its opening the Chapter2.txt file?
Reply:If I'm correct, you need to clear the flag.





Add this line after closing the ifstream:





input.clear();





That should solve your problem.





Edit:


It also wouldn't hurt to check if the file was opened again, much like you did for the first file. Either way, clearing the flags should work.


No comments:

Post a Comment