#include <iostream>
#include <cstdlib>
usingnamespace std;
int generate()
{
int* pin;
pin = newint[rand() % ( 9999 + 1 ) + 1000];
cout << pin << endl;
}
int question()
{
string answer;
cout << "Would you like to generate another PIN? Type 'yes' and press Enter to do so, or type 'no' or any other key and press Enter to close the program." << endl;
getline (cin,answer);
if(answer=="no")delete pin, pin = 0, return 0;
if(answer=="yes")generate(), question();
elsereturn 0;
}
int main(int, char**)
{
generate();
question();
return 0;
}
When I compile this, GCC tells me:
main.cpp: In function ‘int question()’:
main.cpp:21:28: error: ‘pin’ was not declared in this scope
main.cpp:21:42: error: expected primary-expression before ‘return’
main.cpp:21:42: error: expected ‘;’ before ‘return’
I'm no C++ pro, so could one of you smart people help me out?
Your code also does other questionable things. Are you trying to make thousands of ints? Because that's what you're doing.
Or did you mean to just make 1 int and set it to some 4 digit value? If that's the case then why are you bothering with new/delete at all? Why not just use a regular int?
Why do you have your functions returning an int when they don't return anything? Why not make them void?
#include <iostream>
#include <cstdlib>
usingnamespace std;
int* pin;
pin = newint[rand() % ( 9999 + 1 ) + 1000];
int generate()
{
cout << pin << endl;
}
int question()
{
string answer;
cout << "Would you like to generate another PIN? Type 'yes' and press Enter to do so, or type 'no' or any other key and press Enter to close the program." << endl;
getline (cin,answer);
if(answer=="no")delete pin, pin = 0, return 0;
if(answer=="yes")generate(), question();
elsereturn 0;
}
int main(int, char**)
{
generate();
question();
return 0;
}
GCC says:
main.cpp:7:5: error: ‘pin’ does not name a type
main.cpp: In function ‘int question()’:
main.cpp:19:42: error: expected primary-expression before ‘return’
main.cpp:19:42: error: expected ‘;’ before ‘return’
the first error refers to the fact that you are trying to output the whole array to ostream rather than a specific int. (pin isn't an int, its an array of thousands of ints)
Also put the consequences of if in brackets- its better practise and prevents errors
Also, question() will cause pin to display the same value of pin again if the answer is yes because you have defined the value of pin only once. Put the declaration of the value of pin in generate()
so basically put pin= newint [rand() % (9999+1) +1000];
in generate()
finally i dont see the point of creating the array of ints, or is that just a mistake
You should create one int. It should be : pin = newint;
Then use pin = rand() % (9999+1) +1000; in generate.
You should also do this to make the generated numbers more random:
1.Include ctime header file.
2. In any one place add srand (time(NULL))
This will make the randomly generated numbers really random.