C++ homework no idea where to go now

Discussion in 'Programmer's Corner' started by jbarker258, Nov 17, 2011.

  1. jbarker258

    Thread Starter New Member

    Nov 17, 2011
    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...

    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;
    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: Nov 18, 2011
  2. RiJoRI

    Well-Known Member

    Aug 15, 2007
    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.

  3. kubeek

    AAC Fanatic!

    Sep 20, 2005
    I would simply read the input file byte by byte and count them.
  4. Feign

    Active Member

    Mar 30, 2009
    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.

    char characters[21];


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

    int countchars(string& line,string& needle)
    string::iterator it;
    if(*it==*needle) count++;

    something like that..