0
Why does this code show error?
I want to use cin operator to allow user input in classes. Can someone plz explain how to use cin operator in class and within the methods of a class https://code.sololearn.com/cQ28835mgMgg/?ref=app
1 Answer
0
The operator `>>` is a binary operator that takes two operands: an istream on the left and an lvalue on the right. What it does is it extracts data from istream and put it into the lvalue.
What you did wrong here is you didn't set a value for the right hand operator. The function you call does not return a value.
What you want to do is make the `setName` function take a string as an argument and assign it to `name`.
```
void setName(std::string value) {
name = value;
}```
Then, you define the following function globally:
```
std::istream& operator>>(std::istream& lhs, myClass& rhs) {
std::string value;
lhs >> value;
rhs.setName(value);
return lhs;
}```
If you are confused why we are returning `lhs`, it is so that we can something like the following:
`std::cin >> myObj1 >> myObj2;`
More information on operator overloading can be found here:
https://en.cppreference.com/w/cpp/language/operators