-
String class confusions
My string array 'wordbank' is empty after my getword function has run. Please could somebody tell me what I need to know about strings to understand why what I'm trying won't work. Thanks
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string wordbank[100];
int getword(string);
int i = 0;
while(!getword(wordbank[i++]));
cout << "wordbank[0] is empty? " << wordbank[0].empty() << endl;
for (i=0; (!wordbank[i].empty()); i++)
cout << wordbank[i];
}
int getword(string str)
{
cin >> str;
if (str == "Quit")
return 1;
return 0;
}
-
Code:
int getword(string& str)
{
...
}
You have to pass str by reference, so that the modifications are visible to the caller.
-
kmdv's observation is on the mark, but a few other things to watch out for:
- wordbank is an array of 100 words, but your loop that reads into wordbank does not check for this, thus your program is susceptible to buffer overflow.
- getword probably should return a bool instead of an int.
- While reading into wordbank, you increment i. Thus, when the loop terminates, you know the number of words that have been stored. Use this knowledge instead of testing with wordbank[i].empty().
- As a matter of good style, include the parameter name in your forward declaration of getword. Personally, I would rather forward declare getword at file scope rather than in the scope of main.
-
Thanks for your help both!