In C++, string types are much easier to work with than c-style strings which are char arrays. With string types, you can use + to add strings together and == to compare strings. With char arrays, you have to use the functions strcat() and strcmp() respectively to do those tasks. Additionally, strcat() requires that the destination array be big enough to hold both strings plus one additional character('\0') at the end.and does anybody know how tonto's idea works / what it is?
The problem is that when creating an ofstream object in order to write to a file, e.g.
the ofstream constructor requires a char array, i.e. what's inside the parentheses must be a char array. Your statement is incorrect because you can't use + to add a string literal, like "dec", and a char array together. The compiler considers the string literal a char array, so as far as the compiler is concerned, you are adding two char arrays together using +, and you can only use + to add string types together.Code:std::ofstream out("dec_" + argv);
What Tonto's example does is it first turns the string literal into a string type:
Since you can add char arrays to a string type, the code then adds argv to the string type
In regards to what += does, this:Code:( std::string("dec_") += argv )
is equivalent to:Code:string str = "hello"; str = str + " world";
So Tonto's example ends up with this format:Code:string str = "hello"; str += " world";
But, we know that won't do because the ofstream constructor takes a char array as an argument--not a string type. Well, the string class has a function called c_str(), and it returns the string in the form of a char array. So, Tonto's example does this:Code:std::ofstream out(string Type in here)
In summary, the example first turns the string literal "dec_" into a string type, then it adds the char array argv to the string type, and finally it converts the resulting string type to a char array so that the ofstream constructor gets the proper argument type.Code:(std::string("dec_") += argv).c_str()