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

C++ How do I concatenate literals with integers?

本文关键字:整数 连接 起来 文字 C++      更新时间:2023-10-16

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

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

这里不需要串联,让cout为您完成所有繁重的工作 - 毕竟它的<<操作员可以处理int

cout << "Sorry, gcd(" << A << ',' << B << ") is undefined.n";

使用您提供的代码片段的最简单方法:

if( ( A == 0 ) || ( B == 0 ) ){
    cout << "Sorry, gcd(" << A << ',' << B << ") is undefined.n";
    return 0;
}

请注意,您的or声明不正确。你错过了第二个"|">

您可以使用std::stringstream

std::stringstream result;
result << "A string plus a number: " << 33;

如果您想在其他地方使用它,请string

std::string s = result.str();