3

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.

2
  • Yes. Sorry aobut that. Commented Aug 19, 2013 at 17:11
  • 1
    Don't be sorry, just edit the question :) Commented Aug 19, 2013 at 17:12

3 Answers 3

3

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());
Sign up to request clarification or add additional context in comments.

1 Comment

This would work fine, although it still requires me to create another string variable. Granted that variable would go out of scope pretty fast. But I was hoping there would be a way to do it without creating a new variable. thanks for your help anyway. This will work quite nicely
1

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

1 Comment

Na, its very much just to satisfy my own OCD. But thank you for your help.
0

If you really want to avoid unnecessary copies, then you should make Constructor(String szName) into Constructor(const String& szName) - that way, you avoid the string being copied on the way into the constructor (you probably need to copy it inside the constructor).

In one way or another, you will need to store the output from getline in a string (unless you happen to wish to write your own getline that returns a string, but that would still not help avoid copies any more than the basic:

std::string str; getline(cin, str); myClass foo(str);

In fact, using a function that returns the string may lead to another copy (but the compiler will PROBABLY get rid of that extra copy).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.