I am creating variables as such
std::string str1,str2,str3,str4 = "Default";
however the variables do not have the Default value. How can I assign values to variables created this way
str4
will have the value you're looking for. You just didn't initialize the others. Use:
std::string str1 = "Default", str2 = "Default", str3 = "Default", str4 = "Default";
Or, probably better:
std::string str1 = "Default";
std::string str2 = "Default";
std::string str3 = "Default";
std::string str4 = "Default";
If you're concerned about doing so much typing, you can use assignment instead of initialization:
std::string str1, str2, str3, str4;
str1 = str2 = str3 = str4 = "Default";
But that's got different semantics and is (IMHO) a bit hinky.
Generally when you have variable names with numbers in them, an array will be better suited. This gives you the added benefit of using std::fill_n
as well
#include <algorithm>
std::string str[4];
std::fill_n( str, 4, "Default" ); // from link provided by Smac89
// str[0], str[1], str[2], str[3] all set to "Default"
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