CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2010
    Posts
    20

    Simple Counting Program

    Hey guys, I'm trying to create a program that reads from a text file "mytext.txt" and outputs on the screen the number of lines, characters, and words in the file. I have the lines portion working, but can't think of a way to get each character individually, and words?

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    void main() 
    {
    	
    	char line[100];
    	
    	ifstream infile;
    	infile.open("U://mytext.txt");
    
    	if (infile.fail()) 
    	
    	{
    	cout<<"File not found! Exiting."<<endl;
    	exit(0); 
    	}
    	int characters=0, lines=0, words=0;
    
    	while(infile.getline(line, 100))
    	{
    		lines++  ;
    		
    	} 
    	cout<<"The total number of lines in the file is: "<<lines<<endl;
    	infile.clear() ;
    	infile.seekg(0, ios::beg) ; //so that the beginning of the file is being read again
    
    		while(infile)
    	{
    		//not sure what to do here?
    		characters++  ;
    		
    	} 
    	
    	cout<<"The total number of characters in the file is: "<<characters<<endl;
    }

  2. #2
    Join Date
    Sep 2010
    Posts
    66

    Re: Simple Counting Program

    Maybe there is a better way to do this, but this is just one way I thought of:

    Code:
    #include <string>
    #include <fstream>
    #include <iostream>
    
    using namespace std;
    
    int main () {
    	string s;
    	int totalChars = 0, 
    		totalWords = 0, 
    		totalLines = 0;
    
    	ifstream in("test.txt");
    
    	if(!in){
    		cout << "Failed to open input file.";
    		return -1;
    	}
    
    
    	while(getline(in, s, '\n')){
    		totalChars += s.length();
    		totalLines++;
    
    		for(int i = 0; i < s.length(); i++){
    			if(s[i] == ' ')
    				continue;
    
    			totalWords++;
    
    			while(i != s.length() && s[i] != ' ')
    				i++;
    		}
    
    	}
    
    	cout << "Total Words: " << totalWords << endl;
    	cout << "Total Characters: " << totalChars << endl;
    	cout << "Total Lines: " << totalLines << endl;
    
    		return 0;
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured