Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to initialize a std::string before I input it from stdin?

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;
like image 617
alekscooper Avatar asked May 15 '26 18:05

alekscooper


1 Answers

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

like image 64
Arnav Borborah Avatar answered May 18 '26 09:05

Arnav Borborah