vector<string> segmentation fault and skipped input

Hi,

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <ios>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>

using namespace 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;
}
You're trying to access data[data.size()], which is out of bounds.

Also, why is variant (could be named i for index, which would make it meaningful and easier to read) a double?
Ah, because the first member of a vector is vector[0], forgot that.
Nice one, thank you.

You're right, there is no need for it to be a double, changed to int.

That sorts out the segmentation fault, but it still doesn't let me input the word I want to count...
Last edited on
cin received eof, so you need to clear its state: cin.clear();
Topic archived. No new replies allowed.