Home > OS >  How to access the data member of one function into another function inside same class in c
How to access the data member of one function into another function inside same class in c

Time:05-22

I wanted to declare the array of string to the limit provided by user. So I take limit in getData(), and declare the string inside getData function. As a whole I want to take students name and display it in the same class. Sorry for basic question and thank you in advance.

class student
{
    int limit;
public:
    void getData()
    {
        cout<<"Enter the number of students: ";
        cin>>limit;
        string name[limit];
        cout<<"Enter the names of students: \n";
        for(int i=0; i<limit; i  )
          cin>>name[i];
    }
   void showData()
    {
        cout<<"The list of students: \n";
        for(int i=0; i<limit; i  )
            cout<<name[i]<<endl;
    }
};
int main()
{
    student s1;
    s1.getData();
    s1.showData();
    return 0;
}

Here in this function, error comes as "name was not declared in this scope". sorry in advance if it is nonsense.

void showData()
        {
            cout<<"The list of students: \n";
            for(int i=0; i<limit; i  )
                cout<<name[i]<<endl;
        }

CodePudding user response:

One problem with your code is that string name is defined in getData() but not in showData(). What I would do is declare a member variable vector<string> name like you did with int limit. I would use a vector instead of an array because it's easier to code for me.

#include <iostream>
#include <vector>

using namespace std;

class student
{
    int limit;
    vector<string> name;
public:
    void getData()
    {
        cout<<"Enter the number of students: ";
        cin>>limit;
        cout<<"Enter the names of students: \n";
        for(int i=0; i<limit; i  )
        {
            string temp;
            cin>>temp;
            name.push_back(temp);
        }
    }
   void showData()
    {
        cout<<"The list of students: \n";
        for(int i=0; i<limit; i  )
            cout<<name[i]<<endl;
    }
};
int main()
{
    student s1;
    s1.getData();
    s1.showData();
    return 0;
}

Output:

Enter the number of students: 3
Enter the names of students: 
andy
max
rose
The list of students: 
andy
max
rose
  •  Tags:  
  • c
  • Related