Print out Random array

Im trying to randomly print out cars from thestring carnamesArray[30]
depending on how many cars the user wants to race.
Im not quite for sure how to do so, so help would be great, I know the code looks funky, but just go with it. Thanks. :)
(For say, the user wants to race 6 cars, I want it to randomly draw 6 names of cars from the "stringcarnamesArray" and print them out for the user to see)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <cstdlib>
using namespace std;




int main()
{
	string carnamesArray[30] = {"Honda", "Galant", "Ferari", "Mitsubishi", "Hondai", "Volvo", "Eclipse", "Lamborghini", "Porche", "Kid cudi", "Eminem", "50 Cent", "Galant", "Chrysler", "Ford", "Chevrolet", "Dodge", "Fake", "Ram", "Mercadies", "Lexus", "Jaguar", "Benz", "Trans am", "Firebird", "Lady Gaga", "Mini van", "Jeep", "300", "Pringles"};
	string mpg[14] = {"15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28"};
	
	int carsraced;
	
	cout << "Welcome to the race!" << endl << endl;
	system("PAUSE");
	cout << endl << "How many cars would you like to race today?\n";
	cin >> carsraced;
		
		if (carsraced > 15)
	{
		cout << "Theirs a 15 car limit!" << endl;
	system("PAUSE");
	return 0;
	}
	system("PAUSE");
	return 0;
}


EDIT: I've seen alot of stuff like, printf ("%s\n", [rand()carnamesArray%2]

I know what it means and stuff, but it doesnt print out for me.. =/
Last edited on

your syntax is wrong.

printf ("%s\n", carnamesArray[rand() % carsraced].c_str() );

Also don't forget if you are using printf (instead of cout) and printing a string you need to call c.str() on the string.

1
2
3
4
// printing string with printf vs cout.
string s = "Test";
printf( "%s\n", s.c_str() );
cout << s << endl;


Also the % "mod" operator cycles through numbers between 0 and Num-1

1
2
3
// the following will print 0,1,2 over and over until i reaches 10000
for( int i=0; i < 10000; i++ )
  printf( "%d ", i%3 );



Thanks man, I was curious on how to use "for" on this. After realizing that instead of a string array it needs to be a vector. Ive been gone for 3 days though.
Topic archived. No new replies allowed.