Hi guys, I'm writing a weasel program and needed a random character generator, I used a random number generator to give an ascii code for each character, and made a sequence of them, then I realized I needed to include the "space" symbol, but upon inclusion of the new code the compiler tells me my character variable c ins't declared in this scope. Before code:

string genstring (){

    
	string generated_string;
        string stringsize=inputsentance()
	
   
	for (int k=0; k<sentance.size(); k++){ 
	
	
		
		int n = rand() % 25;
		
		char c = char(n+65);
	
		string s;	 	 
		s=s+c;	  	  
		generated_string.append(s);
		s.clear();	
		 
	}
	
    return generated_string;	
}

And after code:

string genstring (){

	string generated_string;
	string stringsize=inputsentance();
	
   
	for (int k=0; k<stringsize.size(); k++){ 
	
		srand(time(0));
		
			int n = rand() % 26;
				 	if (n==26)
				  		{char c = char(32);}
				  	else 
				
						{char c = char(n+65);}
	
		string s;	 	 
		s=s+c;	  	  
		generated_string.append(s);
		s.clear();	
		
	}
		
    return generted_string;	
}

I don't see how the c variable is any different in both.

It's a scoping issue. See those brackets where you declare c inside of them? You can only use c within those brackets. That's the error. You need to declare c on line 2, not lines 13 and 16.

[EDIT]
You don't need to declare it on line 2. Declare it anywhere before line 12.
[/EDIT]

Like VernonDozier said, you are declaring 'char c' out of scope but there are also a few other errors within your program.

You are calling the function srand() at the start of the for() loop on each iteration which results in all the characters being the same. The solution to this is to call srand() once either at the start of this function or at the beginning of main() (I would suggest placing it at the start of main()).

The second problem is the range for your rand() function. You had rand() % 26; which will generate a number from 0 to 25 not 0 to 26. So the solution is to just set your maximum to the maximum value in your range + 1.


I did a bit of tweaking and shortened your append section but for the most part it is the same.

Also notice that srand() is not being called here because it should be at the start of main().

string genstring()
{
	string generated_string;
	string stringsize = inputsentance();

	for( unsigned int k = 0; k < stringsize.size(); k++ )
	{
		char c = rand() % 27 + 'A'; //random from "A-["

		if( c == '[' )
			c = ' ';

		generated_string.append(1, c);
	}
	return generated_string;
}

This is great thank you for all the help! :icon_biggrin:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.