5

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

MistyD
  • 14,915
  • 32
  • 126
  • 215

6 Answers6

9

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.

Carl Norum
  • 210,715
  • 34
  • 410
  • 462
4

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"
clcto
  • 9,370
  • 18
  • 40
  • Actually, this only initialises the first string to "Default". The rest are not initialised – smac89 Sep 10 '13 at 23:52
  • @Smac89 `int a[100] = {0};` initializes all a to 0. Is it different with classes? – clcto Sep 10 '13 at 23:56
  • [Read this](http://stackoverflow.com/questions/1065774/c-c-initialization-of-a-normal-array-with-one-default-value) – smac89 Sep 11 '13 at 00:02
2

How about chaining?

std::string str1, str2, str3, str4;
str1 = str2 = str3 = str4 = "Default";
Thomas Matthews
  • 54,980
  • 14
  • 94
  • 148
2
std::string str1,str2,str3,str4;
str1 = str2 = str3 = str4 = "Default";
ArmenB
  • 1,897
  • 2
  • 20
  • 44
1
std::string str1 = "Default", str2 = "Default", str3 = "Default", str4 = "Default";

Initialize each variable separately, preferably declaring one variable per line.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
-1

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

smac89
  • 32,960
  • 13
  • 112
  • 152