using arguments of argv

Hi guys, I am having problems generating a sequence of random numbers determined by the argv argument

when i write ./random 20

I want it to generate 20 random numbers. The problem is it will only show 2, but the interval from 0-9 works well, will show 4, 5, 6 ,7...random numbers.

Here is my code:

test is a class.
 
test.GenerarPermutacion(argv[1][0]-'0');


1
2
3
4
5
6
7
8

void permutacion::GenerarPermutacion (char argv) {
	int j=0;
	srand((unsigned)time(0));
	for (int i=0; i<argv; i++){
		j=(rand()%512)+1;
		cout << j << endl;
	}


I am sure it the problem must be the argv being a char, but I don't quite understand what is causing the problem, since I understand that -'0' makes the char value be int likewise.
assuming argv[1] has the string "20" (which would be the case if you do ./random 20

argv[1][0] gets you the first character of "20", which is '2'.

argv[1][0]-'0' takes that '2' and subtracts '0' from it to give you 2

Therefore you're only getting 2 random numbers.

A better way to do this would be to use either stringstreams or sscanf:

1
2
3
4
5
6
7
8
9
10
// scanf:
int num;
sscanf(argv[1],"%d",&num);
test.GenerarPermutacion(num);

// stringstreams:
int num;
stringstream ss(argv[1]);
ss >> num;
test.GenerarPermutacion(num);
thanks, thas was indeed the problem ;)
Topic archived. No new replies allowed.