954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Putting my count characters code into a function

Hello! I am working on a problem to count characters (without using strings) and I got my program to work! However, I got it to work before I put the code that counts characters into a function (countChar), which is required for this assignment. I'm not sure I understand how to open the file in main and then reference that file in a function. I am posting both versions of my code. The first works, the second does not display cout in my function, but does exit. Any explanation on how to link the function to the file I'm opening in main would be very much appreciated. Thanks!

#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;

void problems(char*);

void main(void)
{
	const char path[]={"D:\\filepath\\"};
	char fileName[32];
	char nameWithPath[81];
	char text[100];
	char c ;
	int counter=0 ;

	cout<<"Enter the input file name: ";
	cin>>fileName;
	strcat(strcpy(nameWithPath,path),fileName); 

	ifstream inFile;
	inFile.open(nameWithPath);
	if (!inFile.good())
		problems(nameWithPath);

	while(true)
	{
		if(inFile.peek() == -1)
			break;
		c = inFile.get();
		if(c != '\n') 
		++counter;
	}

	cout<<"Number of characters: "<<counter<<endl;
	inFile.close();
}

void problems(char* file)
{
	cerr<<"Problems opening file: "<<file<<endl;
	exit(EXIT_FAILURE);
}

This doesn't work:

#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;

void problems(char*);
void countChars(void);

void main(void)
{
	const char path[]={"D:\\filepat\\"};
	char fileName[32];
	char nameWithPath[81];
	char text[100];
	char c;
	int counter=0;

	cout<<"Enter the input file name: ";
	cin>>fileName;
	strcat(strcpy(nameWithPath,path),fileName); 

	ifstream inFile;
	inFile.open(nameWithPath);
	if (!inFile.good())
		problems(nameWithPath);

	void countChars();

	inFile.close();
}

void problems(char* file)
{
	cerr<<"Problems opening file: "<<file<<endl;
	exit(EXIT_FAILURE);
}
void countChars(void) 
{
	char c;
	int counter=0;
	
	ifstream inFile;
	while(true)
	{
		if(inFile.peek() == -1)
			break;
		c = inFile.get();
		if(c != '\n') 
		++counter;
	}

	cout<<"Number of characters: "<<counter<<endl;
}
engineerchica
Newbie Poster
19 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
 

Pass the inFile to the function.

Also, read this

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

Awesome. Thanks WaltP.

engineerchica
Newbie Poster
19 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: