I need to declare a new string variable in C++ and then read it from the standard input.
Do I have to initialize the string first, or is it an unnecessary step? In other words, which code is better: option 1 or option 2 (or are they the same)?
1)
string s = "";
cin >> s;
string s;
cin >> s;
Well for std::string, it doesn't really matter. Since the default constructor of std::string initializes it with an empty string:
Default constructor. Constructs empty string (zero size and unspecified capacity). (Source)
Both lines essentially do the same thing in terms of behavior. It doesn't really matter whether you pick 1 or 2, but I would say that if the default constructor does the same thing, then the assignment is obsolete.
If you had some sort of an integral type, something without a default constructor, then most people still leave it uninitialized since the input is being taken right afterwards. However, I find it better to initialize such variables with a default value since this handles the case where input fails for some reason (Invalid type, bad stream state, etc.)
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