'Using User Set Variables to Create an Instance of a Class
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 <iostream>
#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();
}
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Anoop Rana |