using references (need help)
I am going through my C++ book and one of the exercises asks you to alter an earlier project using references (to make it more efficient). I have written the program (see below), but when I run the executable, I get a run-time error. Basically the program crashes when it's supposed to tell you a story using all the user input.
I think that it might be a scoping problem...but i'm going through my book to check...
All changes I made are in bold...adding references is the only change.
Code:
//Creates a story based on user input
#include <iostream>
#include <string>
using namespace std;
string& askText(string prompt);
int& askNumber(string prompt);
void tellStory(string& name, string& noun, int& number, string& bodyPart, string& verb);
int main()
{
cout << "Welcome to Mad Lib.\n\n";
cout << "Answer the following questions to help create a new story.\n";
string& name = askText("Please enter a name: ");
string& noun = askText("Please enter a plural noun: ");
int& number = askNumber("Please enter a number: ");
string& bodyPart = askText("Please enter a body part: ");
string& verb = askText("Please enter a verb: ");
tellStory(name, noun, number, bodyPart, verb);
cin.get();
return 0;
}
string& askText(string prompt)
{
string text;
cout << prompt;
cin >> text;
cin.ignore();
string& rText = text;
return rText;
}
int& askNumber(string prompt)
{
int num;
cout << prompt;
cin >> num;
cin.ignore();
int& rNum = num;
return rNum;
}
void tellStory(string& name, string& noun, int& number, string& bodyPart, string& verb)
{
cout << "\nHere's your story:\n";
cout << "The famous explorer ";
cout << name;
cout << " had nearly given up a life-long quest to fine\n";
cout << "The Lost City of ";
cout << noun;
cout << " when one day, the ";
cout << noun;
cout << " found the explorer.\n";
cout << "Surrounded by ";
cout << number;
cout << " " << noun;
cout << ", a tear came to ";
cout << name << "'s ";
cout << bodyPart << ".\n";
cout << "After all this time, the quest was finally over. ";
cout << "And then the ";
cout << noun << "\n";
cout << "promplty devoured ";
cout << name << ". ";
cout << "The moral of the story? Be carful what you ";
cout << verb;
cout << " for.";
}
If you have any questions regarding the code, please ask. I should be at my computer for a few more hours trying to fix this program. Any helpful advice is welcome, thanks again!