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;
}

Pass the inFile to the function.

Also, read this

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.