You are here:

C++/running problems

Advertisement


Question
"/*Hey David Spector, there is a problem. I have written 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 the program. Please do shed some light as to what I have written and why there is a problem with my program. And when you do give me an answer, please take into consideration that I am still a novice in C++ and there are still some terms I need to know to understand 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=i;


}

system("Pause");
return 0;
}


Answer
John , Thank you for your question.

I regret that I am unable to do debugging for people due to the volume of questions received. This kind of problem is usually easy to solve by stepping through the code with your debugger, looking at the values of the variables until you see something wrong. This should show you the exact line of the bug.

(I do not recommend that beginners use the STL. The STL is designed for advanced programmers.)

Your program sometimes ran correctly on my computer. It will not handle empty input correctly.

I had to change

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

to

using namespace std;

to make your program compile under Visual C++.

David Spector

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


David Spector

Expertise

Highly knowledgeable in the C++ language, Visual C++ (MSVC), Windows API, documentation and other quality-assurance techniques, and debugging. Knowledgeable in MFC, COM, GUI design, and object-oriented design.

Experience

I have been a software engineer since 1965. I have been published. My specializations have been: biomedical programming, compiler implementation, and many kinds of Windows programming. I don't do Databases or other business-oriented stuff.

Publications
Windows?/DOS Developer's Journal, ACM SIGPLAN Notices, and Computer Science Press.

Education/Credentials
ICCP Systems Programming Certification
Master's degree equivalent in Computer Science

©2016 About.com. All rights reserved.