So my question is fairly simple (I hope). I currently have a Class with a constructor that looks like this:
Constructor(String szName)
the string will be holding a name; This may be more then one part. So John, John Smith, John H Smith, must all be valid inputs. I know I could do the following:
std::string input;
getline(cin, input);
myClass Foo(input);
and it would work fine. But is there anyway for me to directly send the getline input to my constructor?
Thank You for your help in advance.
Well, if you're fine with making another function, you could do it like this:
std::string readLine()
{
std::string input;
getline(cin, input);
return input;
}
and then initialize your class like so:
myClass Foo(readLine());
There is no point in doing so. It would be just semantic sugar, as string will still require same amout of memory to be stored. If you fear that having additional variable in bigger block of code would increase memory usage you can surround getline call with {} as below:
{
string input;
getline(cin, input);
myClass Foo(input);
}
And the variable will exist only inside such block. But there is no big advantage in doing so (at least not for such simple code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With