2

I am trying to create a program that uses class, arrays, and functions to show information about two students(Name, id#, classes registered). The part I am struggling with is passing arrays to a function. How do I do that?

#include <string>
#include <iostream>
#include <iomanip>
using namespace std;

class Student // Student class declaration.
{
private:
  string name;
  int id;
  string classes;
  int arraySize;

public:
  void setName(string n)
  {
    name = n;
  }
  void setId(int i)
  {
    id = i;
  }
  void setClasses(string c, int num)
  {
    classes = c;
    arraySize = num;
  }
  string getName()
  {
    return name;
  }
  int getId()
  {
    return id;
  }
  void getClasses()
  {
    for (int counter=0; counter <arraySize; counter++) {

      cout << classes[counter] << endl;
    }

  }

};

int main()
{
  //Student 1
  string s1Name = "John Doe";
  int s1Id = 51090210;
  int const NUMCLASSES1 = 3;
  string s1Classes[NUMCLASSES1] = {"C++","Intro to Theatre","Stagecraft"};
  //Student 2
  string s2Name = "Rick Harambe Sanchez";
  int s2Id = 666123420;
  int const NUMCLASSES2 = 2;
  string s2Classes[NUMCLASSES2] = {"Intro to Rocket Science","Intermediate Acting"};
  //

  Student info;

  info.setName(s1Name);
  info.setId(s1Id);
  //info.setClasses(s1Classes, NUMCLASSES1);
  cout << "Here is Student #1's information:\n";
  cout << "Name: " << info.getName() << endl;
  cout << "ID: " << info.getId() << endl;
  //cout << "Classes: " << info.getClasses() << endl;


  info.setName(s2Name);
  info.setId(s2Id);
  // info.setClasses(s2Classes, NUMCLASSES1);
  cout << "\n\nHere is student #2's information:\n";
  cout << "Name: " << info.getName() << endl;
  cout << "ID: " << info.getId() << endl;
  //cout << "Classes: " << info.getClasses() << endl;



  return 0;
}
2
  • 2
    As a beginner, prefer std:.vector to raw arrays. Passing a std::vector is the same as passing an int or std::string. Commented Aug 3, 2016 at 4:51
  • Where in this code are you trying to pass arrays to functions? You can pass a pointer but then you should also pass a length. You can use std::array instead or vector as many others suggest. Commented Aug 3, 2016 at 5:27

5 Answers 5

1

The usual way to pass around variable-length lists in C++ is to use an std::vector. A vector is a single object that you can easily pass to a function, copying (or referencing) its contents. If you are familiar with Java, it's basically an ArrayList. Here is an example:

#include <vector>
#include <string>
using namespace std;

class foo {
private:
  vector<string> myStrings;

public:
  void setMyStrings(vector<string> vec) {
    myStrings = vec;
  }
}

//...

foo myObj;
vector<string> list = {"foo","bar","baz"};
myObj.setMyStrings(list);

If don't want to use the standard library though, you can pass an array C-style. This involves passing a pointer to the first element of the array, and the length of the array. Example:

void processStrings(string* arr, int len) {
  for (int i = 0; i < len; i++) {
    string str = arr[i];
    //...
  }
}

string array[] = {"foo","bar","baz"};
processStrings(array, 3);// you could replace 3 with sizeof(array)/sizeof(array[0])

Passing raw arrays like this, especially if you wanted to then copy the array into an object, can be painful. Raw arrays in C & C++ are just pointers to the first element of the list. Unlike in languages like Java and JavaScript, they don't keep track of their length, and you can't just assign one array to another. An std::vector encapsulates the concept of a "list of things" and is generally more intuitive to use for that purpose.

Life lesson: use std::vector.

EDIT: See @nathanesau's answer for an example of using constructors to initialize objects more cleanly. (But don't copy-paste, write it up yourself! You'll learn a lot faster that way.)

Sign up to request clarification or add additional context in comments.

1 Comment

I just have to add that the sizeof() function returns the size in bytes, which is not necessarily the number of elements of an array. To get the amount of elements in an array devide the byte size of an array by the byte size of a single element or by the byte size of a type of elements that the array stores. Instead of sizeof(array) use: sizeof(array) / sizeof(array[0]) or sizeof(array) / sizeof(std::string)
0

You can pass array of any_data_type to function like this

void foo(data_type arr[]);

foo(arr); // If you just want to use the value of array 
foo(&arr); // If you want to alter the value of array.

Comments

0

Use std::vector. Also, don't add functions you don't need. Here's an example of using std::vector

#include <string>
#include <iostream>
#include <vector>

using std::string;
using std::vector;

class Student // Student class declaration.
{
private:

    vector<string> classes;
    string name;
    int id;

public:

    Student (const vector<string> &classesUse, string nameUse, int idUse) :
        classes (classesUse),
        name    (nameUse),
        id      (idUse)
    {
    }

    void print ()
    {
        std::cout << "Name:    " << name << std::endl;
        std::cout << "Id:      " << id << std::endl;
        std::cout << "Classes: ";

        for (int i = 0; i < classes.size (); i++)
        {
            if (i < classes.size () - 1)
            {
                std::cout << classes[i] << ", ";
            }
            else
            {
                std::cout << classes[i] << std::endl;
            }
        }

        std::cout << std::endl;
    }
};

int main()
{
    Student John ({"C++","Intro to Theatre","Stagecraft"},
                  "John",
                  51090210);

    John.print ();

    Student Rick ({"Intro to Rocket Science","Intermediate Acting"},
                  "Rick",
                  666123420);

    Rick.print ();

    return 0;
}


Name:    John
Id:      51090210
Classes: C++, Intro to Theatre, Stagecraft

Name:    Rick
Id:      666123420
Classes: Intro to Rocket Science, Intermediate Acting

Comments

0

In the private variables of class Student, you are storing a string: String classes; where as you should be storing an array of strings like: String classes[MAX_NUM_CLASSES];

then in the set classes function, pass in an array of strings as the first argument, so it should be :

void setClasses(string[] c, int num)

{

classes = c; //not sure if simply setting them equal will work, rather copy entire array using a for loop

 arraySize = num;

}

This should point you in the right direction

Also, use std::vector instead of string[], it will be easier.

Comments

0

In your current code, you're trying to store an array of strings in a single string variable (classes), which won't work. You need to store the array properly and pass it correctly to your function.

You should use Vectors

#include <string>
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

class Student
{
private:
    string name;
    int id;
    vector<string> classes;  // Use vector instead of single string

public:
    void setName(string n)
    {
        name = n;
    }
    
    void setId(int i)
    {
        id = i;
    }
    
    // Pass vector by reference
    void setClasses(const vector<string>& c)
    {
        classes = c;
    }
    
    string getName()
    {
        return name;
    }
    
    int getId()
    {
        return id;
    }
    
    void getClasses()
    {
        for (const string& cls : classes) {
            cout << cls << endl;
        }
    }
};

int main()
{
    // Student 1
    string s1Name = "John Doe";
    int s1Id = 51090210;
    vector<string> s1Classes = {"C++", "Intro to Theatre", "Stagecraft"};
    
    // Student 2
    string s2Name = "Rick Harambe Sanchez";
    int s2Id = 666123420;
    vector<string> s2Classes = {"Intro to Rocket Science", "Intermediate Acting"};

    Student info;

    // Student 1
    info.setName(s1Name);
    info.setId(s1Id);
    info.setClasses(s1Classes);  // Now this works!
    
    cout << "Here is Student #1's information:\n";
    cout << "Name: " << info.getName() << endl;
    cout << "ID: " << info.getId() << endl;
    cout << "Classes: " << endl;
    info.getClasses();

    // Student 2
    info.setName(s2Name);
    info.setId(s2Id);
    info.setClasses(s2Classes);
    
    cout << "\n\nHere is student #2's information:\n";
    cout << "Name: " << info.getName() << endl;
    cout << "ID: " << info.getId() << endl;
    cout << "Classes: " << endl;
    info.getClasses();

    return 0;
}

1 Comment

Isn't this already covered by the earlier answers?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.