user9638244
user9638244

Reputation:

C++ How do I concatenate literals with integers?

I am trying to concatenate a literal with an integer.

The problem is when using the + operator to concatenate a literal with an integer, it tells me "error: invalid operands of types 'const char*' and 'const char [17]' to binary 'operator+'".

This is the relevant code :

if ( ( A == 0 ) | ( B == 0 ) ) {

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

}

Upvotes: 2

Views: 166

Answers (3)

Javier Iba&#241;ez
Javier Iba&#241;ez

Reputation: 41

You can use std::stringstream:

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

And get a string if you want to use it elsewhere:

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

Upvotes: 4

bcr
bcr

Reputation: 950

The easiest way using the code snippet you provided:

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

Please note that Your or statement was incorrect. You were missing a second “|

Upvotes: 4

scohe001
scohe001

Reputation: 15446

No need for concatenation here, let cout do all the heavy lifting for you--its << operator can handle int's after all!

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

Upvotes: 6

Related Questions