Problem with function and vector syntax

Alright, so I thought I had everything right... my problem is, the function words() doesn't pass the strings adj and noun to the fake() function... I can't figure it out... if I put a cout << adj << noun in the words() function, it gives the random words. I get nothing, though, out of the fake() function. It does compile... I am also getting a segfault (core dumped) error sometimes when I run it. If I choose 5 as my number of entries, one out of every 5 or 6 times it gives the segfault error. It looks like it runs the loop a few times before erroring out. Help?!

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<iostream>
#include<ctime>
#include<string>
#include<fstream>
#include<vector>
using namespace std;

string words(string adj,string noun)
{
ofstream output1, output2;
ifstream txtAdj, txtNoun;
int x, y, z;
string word;
vector<string> adjectLst;
vector<string> nounLst;

txtAdj.open("adjectives.txt");
txtNoun.open("nouns.txt");

while(txtAdj >> word)
{
adjectLst.push_back(word);
}

while(txtNoun >> word)
{
nounLst.push_back(word);
}
x = rand() %1566 + 1;
for ( ; x > 0; x--)
{
adjectLst.pop_back();
adj = adjectLst[adjectLst.size()-1];
}

x = rand() %50 +1;
for ( ; x > 0; x--)
{
nounLst.pop_back();
noun = nounLst[nounLst.size() -1];
}
adjectLst.clear();
nounLst.clear();
}

void fake()
{
string adj, noun;
int entryCnt = 0; 
 
cout << "How many entries do you wish to make? ";
cin >> entryCnt;
 
while (entryCnt > 0)
{
words(adj, noun);
cout << adj << noun << endl;
entryCnt--;
}
}

int main()
{
srand(time(NULL));
fake();
return 0;
}


Thanks in advance!
Line 8: You're passing adj and noun by value. words operates on a copy of the variables passed at line 56. You want to pass by reference instead so that the caller's variables are updated.
So line 8 should read:

 
string words(string& adj, string& noun)


That definitely fixed the returning values! But I am still getting a segfault like every few tries. I get it after 3-6 lines when I type the number of loops in at 100. Any thoughts on that? Both txt files being used have more entries than the pop_back random count.

Thanks again!

EDIT: It may have been my count was off... I dropped the random range further by quite a bit and I don't have any segfaults anymore! I am proud of myself for being on the right track!!! I love this forum and AbstractionAnon, you deserve a hug!!! Or at least a pat on the back =)

Thanks SOOOOOOOO much!!!
Arcie
Last edited on
Topic archived. No new replies allowed.