#include <fstream>  
#include <iostream> 
#include <string>   

using namespace std; 

string getFileName(); 
int numCharsInFile( ifstream &in, int &nLines ); 
int numWordsInFile( ifstream &in, int &nWords ); 

main ()
{
    int nLines,          
        nChar,         
        avgCPL, 
        nWords;         


    ifstream textFile; 
    string fileName; 
    fileName = getFileName(); 
    
    textFile.open(fileName.c_str());

    if(!textFile.is_open())   
    {
        cerr << "Cannot open file: " << fileName << endl << endl;
        exit (0);
    }
    
    nWords = numWordsInFile( textFile, nWords); 
   
    nChar = numCharsInFile( textFile, nLines ); 
    avgCPL = nChar / nLines; 

    cout << "Number of Words: " << fileName<< " is = " << nWords << endl;
   
    cout << "Number of characters: " << fileName<< " is = " << nChar << endl;
    cout << "Number of lines: " << fileName<< " is = " << nLines<<endl;
    cout << "Average characters per line: "<< fileName << " is: " << avgCPL << endl;
	
    system("pause");
    
    textFile.close(); 
}


string getFileName()
 {
    string fileName; 
    cout << "Please enter file name of the input text file (i.e. including the path): ";
    cin >> fileName; 
    cout << endl; 

    return fileName;
 }

int numCharsInFile(ifstream &in,int &nLines )
 {
    int nChar = 0; 
    char ch; 
    nLines = 0; 

    while (in.get(ch)) 
    {
         if (ch != ' ' )
	     {
            if(ch != '\n')
                nChar++;
	        else
	        {
                nLines++; 
	        }
         } 
    }
  
    return nChar; 
}

int numWordsInFile( ifstream &in, int &nWords)
{
    in.clear(); 
    in.seekg(0, ios_base::beg); 
    int numWords = 0 ; 
    char ch; 
    while (in.get(ch)) 
    {      
        if ( ch == ' ' || ch == '\n' || ch == '\t' ) 
        numWords++;    
    }
    
   return numWords; 
}

Dani AI

Generated

Most likely cause: the program hits an integer divide-by-zero when computing the average characters-per-line. The Windows debug pop-up you described is a classic sign of a runtime exception from dividing by zero, and ’s test (both character and line counts reported zero) matches that symptom. Integer division by zero is undefined behavior in C++ (see operator rules).

What to check (concise):

  • Verify the line-counting routine can actually produce a positive line count. If it only increments on newline bytes, a single-line file with no trailing newline will leave the line counter at zero. Also confirm the input stream isn’t left at EOF before a read — reset error flags and the position before a second pass (use clear() and seekg(); see and istream::seekg).
  • Initialize all counters before use. Passing an uninitialized variable by reference is legal but confusing; make sure any out-parameter is set inside the function.
  • Always guard any division where the denominator might be zero. Print or assert the values before dividing so a debugger shows the real cause instead of landing you in an unrelated stack frame (this is why suggested incremental debugging).

Design notes (from replies):

  • Pick one pattern: return computed values or use out-parameters — avoid doing both for the same result (this simplifies reasoning, as hinted).
  • Make main a proper int main and compile with warnings enabled; many problems are caught by turning on -Wall/-Wextra or equivalent.

Quick checklist to fix and verify:

  1. Initialize counters to zero.
  2. Reset the stream before each read if you do two passes.
  3. Check that the line count is > 0 before dividing; handle empty files gracefully.
  4. Run under a debugger or add diagnostic prints to see the exact failing expression.

These steps will pinpoint the failure and prevent the runtime crash.

Recommended Answers

All 9 Replies

Clarify "it does not run". Does it seg fault, or is it getting "stuck" (appears to be doing nothing), or something else?

when i run it...

i input the file name "sample.txt"

then poof

a windows debug window appears and when i click close it just close the app doing nothing..

Just start with some standard debugging. Comment out the entire code and run it. If that is successful, uncomment out a little and run it again, uncomment a little more and run it again, etc. until you get an error. After doing that you will know in what line of code your error lies, and you can try to take care of it.

i got the error in this part...

string getFileName()
 {
    string fileName; 
    cout << "Please enter file name of the input text file (i.e. including the path): ";
    cin >> fileName; 
    cout << endl; 

    return fileName;
 }

but i don't see any errors in that part... im wondering now...

well i am an idiot so dont believe anything i have to say.
i copy and pasted your code and used basically an essay i wrote last term... what your numCharsInFile function returned was:
0 for nChar
0 for nLine

therefore avgCPL = nChar / nLines; is 0/0 which is illegal..
i didnt get an error where you got one though...

read the windows error message if it says: Integer division by zero. then i helped. if not i suck major balls

without trying to understand the logic i can tell u a few things ..

> change 'main' to 'int main'

>
change
nWords = numWordsInFile( textFile, nWords);
to
only
numWordsInFile( textFile, nWords);
&
int numWordsInFile( ifstream &in, int &nWords)
to
void numWordsInFile( ifstream &in, int &nWords);

as here you'r passing nWords by reference so you dont need to return anything from this function, nWords will automatically have the calculated value as its a reference.

similary for the other function also.

3> no need to create local variables in these functions, manipulate the reference directly.

thank you so much! my problem is solved! thank you so much everyone!!!

What was the culprit?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.