I'm teaching myself C++ with "Accelerated C++" (Koenig/Moo) and struggling with an exercise in Chapter 4, question 4-5
Quote:
Write a function that reads words from an input stream and stores them in a vector.
Use that function to write a program that counts the number of words in the input and to count how many times each word occurred.
|
I've also set myself the extra task of using setw() to make the output neat but to do so I need to calculate the length of the longest string:
I've written the following:
Code:
#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <string>
#include <vector>
using std::cin; using std::cout;
using std::endl; using std::max;
using std::sort; using std::string;
using std::vector; using std::istream;
istream& word_store(istream& in, vector<string>& ws, string::size_type& maxlength)
{
if (in) {
ws.clear();
string x;
string::size_type maxlength = 0;
while (in >> x){
ws.push_back(x);
maxlength = max(maxlength, x.size());
}
in.clear();
}
return in;
}
int main ()
{
vector<string> words;
string::size_type maxlen;
word_store(cin,words,maxlen);
typedef vector<string>::size_type vec_sz;
vec_sz wc = words.size();
cout << "You entered " << wc << " words" << endl;
cout << "And the longest word was " << maxlen << " characters long." << endl;
sort(words.begin(), words.end());
//Sort as a preliminary to counting amount of times each used
cout << "And here they are sorted in ascii order..." << endl;
for (vec_sz i = 0; i != wc; ++i){
cout << words[i] << endl;
}
;
return 0;
}
It works exactly as I'd hoped apart from one thing: "maxlen" always returns zero and I'm baffled.
I'm probably trying to run before I can crawl but I don't understand why passing the vector "words" as a reference to the function enables the function to modify it but the same thing does not happen when I pass the reference "string::size_type&".
Testing within the function "word_store" reveals that the internal variable "maxlength" is calculated correctly. Since "maxlength" is created as a pass by reference from "maxlen" I thought (naively) that all changes to "maxlength" should modify "maxlen" but this does not seem to be the case.
I'm sure this is an idiotic beginner's question but if anyone more experienced could throw some light on this for me I'd be grateful. Thanks in advance.