1 Replies - 2789 Views - Last Post: 04 October 2012 - 01:38 PM

#1 PsychoCoder   User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1659
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Count characters in a file

Posted 23 November 2009 - 11:13 AM

Description: Put code into a console application and runThis snippet counts the number of characters (minus spaces and new line characters) in a specified text file.
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;

void CountCharactersInFile()
{
	//variables needed
	int space = 0;
	int len;
	string fileName = "";
	string str = "";
	string tmp = "";

	//variable for reading our text file
	ifstream inFile;

	//ask for the name of the file (including the path)
	cout << "Please provide a file name to be opened (include path):" << endl;
	getline(cin, fileName);

	//open the file
	inFile.open(fileName.c_str());

	//here we check to make sure the file opened successfully
	if(!inFile)
	{
		//something went wrong
		cout << "Unable to open file" << endl;
		exit(1);
	}
	else
	{
		//here we will read the entire file into a string variable
		//going this route removes new line characters (we dont want to
		//count those as characters
		getline(inFile, str);
		while(inFile)
		{
			str += tmp;
			getline(inFile, tmp);
		}

		//get the length of the string (this will be
		//used when looping through the string)
		len = str.length();

		//now loop through the entire length of the string
		//looking for spaces
		for(int i = 0; i < len; i++)
		{
			//check if this character is a space, if
			//so then increment our counter
			if(isspace(str.at(i)))
				space ++;
		}
	}	
	
	//print the results
	printf("nNumber of characters %d", (len - space));
}


Is This A Good Question/Topic? 0
  • +

Replies To: Count characters in a file

#2 snowingCa   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 04-October 12

Re: Count characters in a file

Posted 04 October 2012 - 01:38 PM

I tried to run this code this a consolde, but it said ERROR the line 30 exit(0 it is not in the scope. How I can fix it?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1