Assigning user input to a private data member.

//Class definition filler here

private:
int digit;

//main function

cout << "Enter a digit: ";
cin >> ???


How would I get cin to assign what the user inputs to the private data member digit?
You'd need a function in your class that will do it for you. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

class A
{
    int digit;
public:
    void setDigit(int d) { digit = d; }
};

int main()
{
    A a;
    int n;
    std::cout << "Enter a digit: ";
    std::cin >> n;
    a.setDigit(n);
    
    return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class A { 
   int num; // private by default
public:
   void set_num(int digit) { num = digit; }
   int get_num() const { return num; }
};

int main()
{
   A obj;
   int digit = 0;
   
   std::cout << "Enter a digit"
   std::cin >> digit;
   std::cin.ignore();
   
   obj.set_num(digit);
   
   std::cout << "num in obj is " << obj.get_num();

   return 0;
}


You really need to do more wokr if you don't know even this basic element of classes: http://www.cplusplus.com/doc/tutorial/classes/
Thank you very very much to the both of you.

This really helped me out.
Topic archived. No new replies allowed.