Hi, im currently trying to write a program which counts the characters in an input file. I need it to count the total characters, the non-blank characters and the alphabetic characters. And then show the statistics of each.

I have both the total characters and alphabetic characters working correctly but for some reason I cannot get it to count the non-blank characters using the isspace command. I used breakpoints to determine that the code is not reading the blank spaces from the input file.

Could anyone please tell me where i'm going wrong?

Here is my code:

// LabReport9Q1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cctype>
using namespace std;

void countchars(ifstream& input, ofstream& output);

int _tmain(int argc, _TCHAR* argv[])
{


ifstream input_stream;

input_stream.open("input.dat");

if (input_stream.fail( ))
{
cout << "Input file opening failed.\n";
exit(1);
}

ofstream output_stream;

output_stream.open("output.dat");

if (output_stream.fail())
{
	cout << "Output file opening failed. \n";
	exit(1);
}

countchars(input_stream, output_stream);


return 0;
}

void countchars(ifstream& input, ofstream& output)
{
	char next;
	double blanks = 0, totalnonblanks, alpha = 0, numerics = 0, total;
	    
	while (input >> next)
    {



	if (isalpha(next))
	{
		alpha++;
    }
	
	if (isdigit(next))
	{
	numerics++;
	}

	if (isspace(next))
	{
		blanks++;
	}

	}

		total = alpha + numerics + blanks;
		cout << "The total number of character occurences is: " << total << endl;
		
		totalnonblanks = alpha + numerics;
		cout << "The total number of non-blank characters is: " << totalnonblanks << endl;

		cout << "The total number of alphabetic characters is: " << alpha << endl;
}

Thanks,

Thunder

The >> operator skips over whitespace automatically.

One alternative could be to capture each line of input from the file individually as a string, using the getline function.

std::string my_string;
while( std::getline( input, my_string ) )
{
    //TODO: Counting
}
This article has been dead for over six months. Start a new discussion instead.