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"
How about chaining?
std::string str1, str2, str3, str4;
str1 = str2 = str3 = str4 = "Default";
std::string str1 = "Default", str2 = "Default", str3 = "Default", str4 = "Default";
Initialize each variable separately, preferably declaring one variable per line.
Method using some C++11 features:
#include <iostream>
#include <string>
#include <algorithm> //for_each
#include <iterator> //begin, end
using std::string;
int main() {
string strs[4];
std::for_each (std::begin(strs), std::end(strs), [](string &str) {
str = "Default";
});
for (string str: strs)
std::cout << str << "\n";
return 0;
}
One of the most significant aspects of this code is the lambda function. I had just read about them and had to try it out. Here is a link if you are interested in learning more