C++ homework no idea where to go now

Thread Starter

jbarker258

Joined Nov 17, 2011
1
I've been sitting here for 2 hours trying to figure out where to go with this code. I guess I just don't understand how strings work or how to use them at all...

Assignment
Write a program that reads in a text file and calculates the average number of non-space characters per line. Note: a. A text file, hw7dataf11.txt, is provided along with the assignment. b. The program can be divided into two parts: i. A function that receives a string and returns the count of the characters in the string. ii. The main function performs tasks like openning the file, adding the total characters and calculating the average.

My current code...

#include <iostream>
#include <fstream>

using namespace std;

int charcount(char characters[]){


}

int main()
{
ifstream inputFile;
inputFile.open("hw7dataf11.txt");
char characters[21];
int total = 0;
while (!inputFile.eof()){
inputFile >> characters;
total = total + charcount(characters);
}





return 0;
}


Seems like i just need to know how to count characters in a string now and fill in the function
Not asking anyone to finish it just need to know wtf to do now
 
Last edited:

RiJoRI

Joined Aug 15, 2007
536
While I'm not familiar with C++, you'd better hope that there are no more than 20 characters in your input file!

After reading in the characters, terminate the string with a NUL '\0'.

Does inputfile read one character?

Personally, I'd use strlen() -- or whatever it's C++ name is. (Lazy Programmer Syndrome.) Of course, if it's a teacher torturing you :), then with a NUL-terminated string you just walk the string, counting characters until you hit the NUL.

I'd also use a predefined string rather than needing to worry about file access, at least until my function was functioning correctly. AND you'd better be passing a pointer to your string to your function.

--Rich
 

Feign

Joined Mar 30, 2009
50
I'm guessing you could use a good c++ reference, http://www.cplusplus.com/reference/

That is not actually a string, it is an array of type char.
http://www.cplusplus.com/reference/string/string/

char characters[21];

becomes

string line; // I hate typing characters the IDE's try to highlight it

int countchars(string& line,string& needle)
string::iterator it;
it=line.begin();
while(it!=line.end())
if(*it==*needle) count++;
it++;

something like that..
 
Top