#include<iostream>
#include<fstream>
#include<time.h>
#include <cstdlib>
usingnamespace std;
void generate_num(int a)
{
srand(time(NULL));
a=rand() % 10+1;
}
int main()
{
string ans;
int tries=0;
int num_re;
int num;
cout<<"#############WELCOME TO THE GUESSING GAME##################"<<endl;
cout<<endl;
cout<<endl;
cout<<"Type rules for seeing what the rules are, if you know the rules type con"<<endl;
get_ans:
cin>>ans;
if (ans=="rules" || ans=="RULES");
{
cout<<"The computer generates a random number (1-10) and you have to find it"<<endl<<endl;
cout<<"Each time your computer will tell you how close you are finding the number"<<endl<<endl;
cout<<"If your number is smaller it will write smaller if it's bigger it will write bigger"<<endl;
cout<<"At the end it will write how many tries you did to find the number"<<endl;
cout<<"Now type con for continuing"<<endl;
goto get_ans;
}
elseif (ans=="con" || ans=="CON") // here's the error
{
generate_num(num);
cout<<"Try to find the number(1-10)"<<endl;
get_num:
cin>>num_re;
if (num_re==num)
{
cout<<"You have found it after"<<tries<<"try/ies"<<endl;
return 0;
}
elseif(num_re>num)
{
cout<<"This number is bigger try again"<<endl;
tries++;
goto
}
elseif (num_re<num)
{
cout<<"This number is smaller try again"<<endl;
tries++;
goto get_num;
}
}
}
Actually i recommend using goto instead of other stuff when its needed.People says goto makes your code harder to understand but in your code its a lot easier to understand bu using goto instead of loops.
He says the semicolon, not the || operator if (ans=="rules" || ans=="RULES") ; // <== Semicolon
the compiler sees your code as :
1 2 3 4 5 6 7 8 9 10 11
if( ans == "rules" || ans == "RULES" )
; // <== the compiler thinks this is the only statement for if()
// semicolon w/o statement is valid
{
// you are creating a local scope here, beetween { }
}
elseif { // <== else if w/o if
}
On the topic of the gotos, they really do make your code harder to understand, especially if they aren't properly indented or separated to show off that they have a colon following them rather than a semicolon. For example, in your code, it took me a while to work out where your get_num tag was. Yes, goto's can be useful sometimes, but often they are just confusing and are just as easily replaced by loops or functions.
Also, only call srand once in your program. This is because otherwise the chance of you getting the same random number, or numbers that can be connected, is greatly increased. And you do realise that 'num' will be filled with junk, too: generate_num is only modifying a copy of num. Instead, either make it return an integer or take the value by reference.