C ++如何将整数文字连接起来?

时间:2018-04-12 20:40:12

标签: c++

我正在尝试将文字与整数连接起来。

问题是当使用+运算符将文字与整数连接时,它告诉我" 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;

}

3 个答案:

答案 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();