Loop in Non-Member Function from Class
May 9, 2014 at 2:58am UTC
Need help on this! I am trying to use a loop with an array within this non-member function. How would I call an array and then use it to loop starting with rov.getName()?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void displayAllRoverData(Rover rov)
{
cout << left << setw(15) << setfill(' ' ) << "Rover" ;
cout << left << setw(15) << setfill(' ' ) << "X-Position" ;
cout << left << setw(15) << setfill(' ' ) << "Y-Position" ;
cout << left << setw(15) << setfill(' ' ) << "Direction" ;
cout << left << setw(15) << setfill(' ' ) << "Speed" ;
cout << endl;
cout << left << setw(20) << setfill(' ' ) << rov.getName();
cout << left << setw(15) << setfill(' ' ) << rov.getXCoordinate();
cout << left << setw(15) << setfill(' ' ) << rov.getYCoordinate();
cout << left << setw(12) << setfill(' ' ) << rov.getDirection();
cout << left << setw(15) << setfill(' ' ) << rov.getSpeed();
cout << endl;
}
May 9, 2014 at 3:31am UTC
Do you want to pass an array to this method or process an array before this method call?
Examples:
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 32 33 34 35 36 37 38 39 40 41
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void insertRandom(int i[])
{
for (int j=0;j<10;j++)//I knew the size was 10!
{
i[j] = rand()%10;
}
}
void myPrint(int i[])
{
cout<<"Passed an array" <<endl;
for (int j=0;j<10;j++)//I knew the size was 10!
{
cout<<"Array[" <<j<<"]: " <<i[j]<<endl;
}
}
void myPrint(int i)
{
cout<<i<<endl;
}
int main()
{
srand(time(0));
int i[10];
insertRandom(i);
myPrint(i);
cout<<"Passed an integer" <<endl;
for (int j=0;j<10;j++)//I knew the size was 10!
{
cout<<"Array[" <<j<<"]: " ;
myPrint(i[j]);
}
return 0;
}
Example of your call method for as pass by array object:
displayAllRoverData(rov);
Example of your header as a pass by array object:
void displayAllRoverData(Rover rov[])//You must know the size of the array!
Example of body code as passed by array object:
1 2 3 4 5
for (int i=0;i<YOURSIZE;i++)
{
//... Skipping
cout << left << setw(20) << setfill(' ' ) << rov[i].getName();
}
-----
Example of your call method for as pass by single object:
1 2 3 4
for (int i=0;i<YOURSIZE;i++)
{
displayAllRoverData(rov[i]);
}
Header and body code would be what you had.
Topic archived. No new replies allowed.