I am creating a text based RPG, nothing special, I am still a beginner, and I was wondering how I would be able to make global variables recognizable by multiple functions after being changed in the first function. For example...
#include <iostream>
usingnamespace std;
//Functions
int character();
int storyline();
//Global Variable
char name;
//function sequence
int main(){
character();
storyline();
return 0;
}
//Character creation function
int character(){
cout << "Please enter your name: ";
char name[20];
cin >> name;
cout << "Your name is: " << name << "\n" << endl;
return 0;
}
//Storyline function
int storyline(){
cout << name << " begins his journey to..." << endl;
return 0;
}
/*The problem I am having is that after the user inputs their name into the
character selection function, it no longer recognizes it in the storyline
function (Notice how when you run the program there is a blank where your
name should be). I am looking for a way to fix it and if anyone thinks they
can help me it it would be much appreciated!*/
In your character function, you're not storing it the global variable called name. You're storing it in a local variable that you've also called name, which you've declared on line 21. This local variable called name hides the global variable called name.
In any case, global variables are a very bad habit, that can cause all kinds of problems in your code. I strongly recommend not using them.