not enough to declare in main?

My code:

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

char randomChar();

int main(){

const int SIZE = 4;
const int LETTERS = 6;

cout << randomChar();

return 0;
}

char randomChar(){
srand((NULL));
return (char)(65 + rand()%LETTERS);
}

I get an error which says: error C2065: 'LETTERS' : undeclared identifier.

Isn't it enough to declare Letters in main?

When I write the function with: char randomChar(const int LETTERS) everywhere I know have nothing, the function always gives me the number C. But I want it to give me random numbers. What have I done wrong?
the scope of LETTERS is just main, if you want to make it global, move it before main

http://www.cplusplus.com/doc/tutorial/variables.html (scroll to Scope of variables)
Last edited on
ahh! Thanks!

Can you se why my randomChar function only gives me the letter C?
Because you are calling srand() in that function, try moving the srand in main and give it time(0) as argument:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{

     const int SIZE = 4;
     const int LETTERS = 6;

     srand( time(0) );//<---

     cout << randomChar();

     return 0;
}

char randomChar()
{
     return (char)(65 + rand()%LETTERS);
}
Thanks! that worked! well, almost. I only want letters for A to G. But I get som strange signs as well. Can you see way? I have tried without srand, but that didn't make things any better.

Do you know why I have to have srand() in main instead of in the function? I think it has worked in functions before. But maybe I remember wrong.
What signs you get?

srand sets the random seed and if you change it each time you call rand is likely you will get the same result
Topic archived. No new replies allowed.