Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using getline to pass a string to an object without using an extra string variable

Tags:

c++

getline

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.

like image 381
Mo H. Avatar asked Aug 25 '26 04:08

Mo H.


2 Answers

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());
like image 76
Jashaszun Avatar answered Aug 26 '26 17:08

Jashaszun


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).

like image 41
jaboja Avatar answered Aug 26 '26 17:08

jaboja