我有一个用 C++ 编写的两个测试程序的示例。第一个工作正常,第一个错误。请帮我解释一下这是怎么回事。
#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;
}
它打开“test.txt”并写入数据,没问题。然而,这不会:
#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;
}
第二个程序的唯一区别是“rpcpassword”已移至下一行。
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="
最佳答案
C++ 中的字符串文字 ("foo"
) 不是 string
类型;它是 const char[x]
类型,其中 x
是字符串文字的长度加 1。并且字符数组不能与 + 连接
。但是,字符数组可以与字符串
连接,结果是一个字符串
,它可以进一步与字符数组连接。因此,"a"+ functionThatReturnsString() + "b"
有效,但 "a"+ "b"
无效。 (请记住,+
是左结合的;它首先应用于最左边的两个操作数,然后应用于结果和第三个操作数,依此类推。)
关于c++ - 为什么这些字符串不会在 C++ 中连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28356983/