I have an example of two test programs I wrote in C++. The first one works fine, the first one errors. Please help me to explain what is going on here.
#include <iostream> #include <string> #include <stdint.h> #include <stdlib.h> #include <fstream> using namespace std; string randomStrGen(int length) { static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; string result; result.resize(length); for (int32_t i = 0; i < length; i++) result[i] = charset[rand() % charset.length()]; return result; } int main() { ofstream pConf; pConf.open("test.txt"); pConf << "rpcuser=user\nrpcpassword=" + randomStrGen(15) + "\nrpcport=14632" + "\nrpcallowip=127.0.0.1" + "\nport=14631" + "\ndaemon=1" + "\nserver=1" + "\naddnode=107.170.59.196"; pConf.close(); return 0; } It opens 'test.txt' and writes the data, no problem. This, however, does not:
#include <iostream> #include <string> #include <stdint.h> #include <stdlib.h> #include <fstream> using namespace std; string randomStrGen(int length) { static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; string result; result.resize(length); for (int32_t i = 0; i < length; i++) result[i] = charset[rand() % charset.length()]; return result; } int main() { ofstream pConf; pConf.open("test.txt"); pConf << "rpcuser=user\n" + "rpcpassword=" + randomStrGen(15) + "\nrpcport=14632" + "\nrpcallowip=127.0.0.1" + "\nport=14631" + "\ndaemon=1" + "\nserver=1" + "\naddnode=107.170.59.196"; pConf.close(); return 0; } The only difference in the second program is that 'rpcpassword' has been moved to the next line.
matthew@matthew-Satellite-P845:~/Desktop$ g++ test.cpp test.cpp: In function ‘int main()’: test.cpp:23:6: error: invalid operands of types ‘const char [14]’ and ‘const char [13]’ to binary ‘operator+’ + "rpcpassword="
std::stringhasoperator+overloaded for concatenation withconst char*.randomStrGen(15), it will not only compile properly but use less memory and run faster.