this program is supposed to get a file throught CMD input redirection, and i have it working, but the function for average seems to keep giving me the wrong number. i keep running through it on paper and i dont get the same answer that the program gives me. can anyone see a reason as to why that might be happening?
sorry for not explaining properly, it's not calculating the average of a set of values, it's calculating average word length of set of words, i need to get the total number of letters in all words divided by the number of words. if there's a simpler way to do that then the function above, do tell.
#include <iostream>
#include <string>
#include <algorithm>
double avgWordLength(const std::string& string) {
//this function assumes that the string has less than or equal to ~65535 spaces
//it also assumes that the string doesn't begin with a space (words are separated by spaces).
//does not discriminate between alphabetical and non-alphabetical characters.
//but, obviously, it discriminates against spaces.
unsignedshort nWords = std::count(string.begin(), string.end(), ' ')+1;
return ((string.size()-(nWords-1))/(double)nWords);
}
int main(int argc, char* argv[]) {
std::string string = "This is a string with words in it";
double avg = avgWordLength(string);
std::cout << "The average word length is " << avg << " characters." << std::endl;
std::cin.get();
return 0;
}
You would need to process the string before passing it to the avgWordLength() function, unless, like in the example above, your string is guaranteed to meet the restrictions of the avgWordLength() function (valid alphabetical characters, no excessive white space, etc).