Ok, so I know this is a very basic problem, and so I'm a little ashamed of myself:P
Anyway, this is a little text rpg I started coding this morning. However, when I
hit '2' to find potions, my compiler says 'e' is not initialized. I've played around with this code and I can't figure out why this is happening, so I thought I would ask you guys! Also, a few things:
1. I know my variables are sloppy, but I just haven' gotten around to cleaning them up.
2. My code isn't complete by any means, so it might also look sloppy, please don't criticize!
Thanks.
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <string>
int main()
{
usingnamespace std;
int a;
int b;
int c;
int d;
int x;
int e;
int random_number;
naming:
string mystr;
cout<<"--------------------------------------------------------------------------------"<<endl;
cout<<endl;
cout<<endl;
cout<<"Enter the player's name: "<<endl;
getline (cin, mystr);
cout<<"Is "<< mystr <<" ok?"<<endl;
cout<<"Press '1' to confirm and '2' to rename"<<endl;
cin >> b;
if (b == 1){
main_menu:
cout<<endl;
cout<<"Where would you like to go?"<<endl;
cout<<"----------------------------------"<<endl;
cout<<"1. Home"<<endl;
cout<<"2. Find Potion"<<endl;
cin >> c;
if (c == 1){
cout<<"You are home"<<endl;
goto main_menu;
}
}
if (c == 2){
random_number = (rand()%5)+1;
cout<<"You have found "<<random_number<<" potions!"<<endl;
e = random_number + e;
cout<<"You now have "<<e<<" potions!"<<endl;
goto main_menu;
}
if (b == 2)
goto naming;
system("pause");
return 0;
}
e = random_number + e; At this point in your code what does 'e' equal? The compiler doesn't know because you haven't instructed it yet, initialize all your variables just to be safe.
And for the love of everything that is good in this world rename your variables, if not for anyone but yourself! ;)
You are taking e = random_number + e; But what was e? It starts off unitialized. On some compilers, this will only give you an error in which case e is something very random and garbagy. In line 17, replace int e; with int e=0;
ahhh oh my god! I'm an idiot haha sorry about wasting a whole topic on this. Just some sloppy stupid coding on my part:P and what should I rename them to? Just wondering!
Also, if you don't mind me asking, when I press 2 to rename my character at the beginning of the code, it runs through this
1 2 3 4 5
cout<<"Enter the player's name: "<<endl;
getline (cin, mystr);
cout<<"Is "<< mystr <<" ok?"<<endl;
cout<<"Press '1' to confirm and '2' to rename"<<endl;
cin >> b;
without asking me the player's name again. I imagine its a problem with getline, but I have no idea. So how do I tell it to wait for me to enter the name again?
Loops are extremely confusing to me, possibly because i haven't found anyone that has explained it really well, and it seems like goto statements are much easier to me. Is there a problem with using goto over do while loops? Or is it ok to use?