I'm pretty new to C++ and am working my way through some tutorial exercises. I am stuck on an exercise where I am supposed to use vectors and push_back to count the number of times a specific word occurs in a set of words.
I get a segmentation fault at end of file when I finish the data input. If I change all the strings to doubles (so the program instead counts how many of a specific number there are in a set of numbers), this part of the program runs fine.
However then I hit my second problem, after all the data is entered it skips the input for entering the number that is supposed to be counted, taking it as 0. If I change the order the program works in, so that this value is taken before the data set is defined, then there is no problem here, but I would really like to know why it won't let me do it this way around.
Any help showing me what I'm doing wrong in either area would be really appreciated!
I'm using Xcode as my compiler in case that is relevant, and here is my full code:
#include <iostream>
#include <ios>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>
usingnamespace std;
int main ()
{
//defines variables for the data input
string x;
vector<string> data;
cout << "Enter several words followed by end of file: ";
//gets data
while (cin >> x) {
data.push_back (x);
}
//terminates the program if no data is entered
if (data.size() == 0) {
cout << endl << "You must enter data. ""Plesase try again." << endl;
return 1;
}
//defines variables for the count
string word;
double variant = data.size();
double count = 0;
//gets the word to be counted
cout << "Type the word you wish to count: ";
cin >> word;
//counts the number of times the word occurs in the data
while (variant > 0){
if (word == data[variant]){
++count;
}
--variant;
}
cout << "There are " << count << " instances of the word " << word << " in the data set given.";
return 0;
}