C++/help

Advertisement


Question
"/*Hey Dharmender Rai, there is a problem. I have writtem a program which will count the number of times a word appears but for some reason, Dev-bloodshed the compiler for C++ that I am using doesn't tell me what the problem is even though I am able to run it. Please do shed some light as to what I have written and why there is a problem with my program. Thank you for any help you may provide.*/

#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
#include <algorithm>

using std::vector;
using std::endl;
using std::cin;
using std::cout;
using std::string;

int main(){

vector<string> words;
string word;
while (cin >> word){
     words.push_back(word);
     }

     sort(words.begin(), words.end());


typedef vector<string>::size_type vec_sz;
vec_sz i = 0;

int count = 0;
while(i!=words.size()){
vec_sz num = 0;
string theword = words[i];
while(theword==words[i]){
++num;
++i;
}
cout << "The word " << theword << " appears " << num << " times" << endl;
++i;


}

system("Pause");
return 0;
}


Answer
Hi John,
    Instead of typedef vector<string>::size_type vec_sz;
please go for iterators.

vector <string> ::iterator iter = words.begin();

for (; iter != words.end; ++ iter)
{
// your logic for counting.

}

Hope this helps.

- RaiD

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Dharmender Rai

Expertise

I can answer general and system level C/C++ questions.

Experience

I have 5 years of experience in C++.

©2016 About.com. All rights reserved.