我正在尝试将文字与整数连接起来。
问题是当使用+运算符将文字与整数连接时,它告诉我" error: invalid operands of types 'const char*' and 'const char [17]' to binary 'operator+
'"。
这是相关代码:
if ( ( A == 0 ) | ( B == 0 ) ) {
cout << "Sorry, gcd(" + A + ',' + B + ") is undefined.\n";
return 0;
}
答案 0 :(得分:6)
不需要在这里进行连接,让cout
为您完成所有繁重的工作 - 毕竟<<
运营商可以处理int
!
cout << "Sorry, gcd(" << A << ',' << B << ") is undefined.\n";
答案 1 :(得分:4)
使用您提供的代码段的最简单方法:
if( ( A == 0 ) || ( B == 0 ) ){
cout << "Sorry, gcd(" << A << ',' << B << ") is undefined.\n";
return 0;
}
请注意,您的or
声明不正确。你错过了第二个“|
”
答案 2 :(得分:3)
您可以使用std::stringstream
:
std::stringstream result;
result << "A string plus a number: " << 33;
如果您想在其他地方使用它,请获取string
:
std::string s = result.str();