Home > Back-end >  Using User Set Variables to Create an Instance of a Class
Using User Set Variables to Create an Instance of a Class

Time:05-16

I was wondering if anyone had any advice on how to take a user input from a std::cin and enter it into a variable. The variable would be used to add an object to a class. Thanks!

This is the code I tried but it did not seem to work:

#include <string>
#include "POI.h"
std::string create_file;
int main() {
std::cout << "Name the File You Would Like to Create: ";
std::cin >> create_file;
POI create_file;
create_file.poi_add(create_file, 1, 12, 7, "unknown");
std::cout << create_file.poi_name();
}

CodePudding user response:

Yes, you can use operator overloading. In particular, you can overload operator>> as shown below. With this you can directly use std::cin with a POI type object.

class POI 
{
   private:
       std::string name ;
  //overload operator so that std::cin can be used with this class 
  friend std::istream& operator>>(std::istream& is, POI&);
};
std::istream& operator>>(std::istream& is, POI& obj)
{
    is >> obj.name ;
    
    //check if input succeded 
    if(is )
    {
        //do somethind 
    }
    else 
    {
        obj = POI(); //leave the object in default state;
    }
    return is;
}
int main()
{
    POI p; 
    std::cin >> p;//this will use the overloaded operator>>
    return 0;
}

Note that the if and else is provide to validate if the input succeeded. If the input fails, then the object is left in a default state.


Additionally note that your inner variable create_file shadows the outer variable with the same name.

CodePudding user response:

Thank you, Anoop Rana, for you detailed answer. However, I am pretty new to coding, and I was wondering if you could explain, in beginner terms, what friend is and what operator is. Also, are the &s references? The final two questions I have are: What does is >> obj.name mean? Does it mean that "is" is being assigned to the instance name? But then where does the obj part come from? Ok. My final question is about std::cin >> p;. Does this take the user input and use that to fill all "p" attributes? What if you have multiple attributes and not just "name"? Sorry I am so confused, I am just not very experienced in c or coding in general.

class POI 
{
   private:
       std::string name ;
  //overload operator so that std::cin can be used with this class 
  friend std::istream& operator>>(std::istream& is, POI&);
};
std::istream& operator>>(std::istream& is, POI& obj)
{
    is >> obj.name ;
    
    //check if input succeded 
    if(is )
    {
        //do somethind 
    }
    else 
    {
        obj = POI(); //leave the object in default state;
    }
    return is;
}
int main()
{
    POI p; 
    std::cin >> p;//this will use the overloaded operator>>
    return 0;
}
  •  Tags:  
  • c
  • Related