coolguy123
coolguy123

Reputation: 5

C++ error: invalid conversion from 'int' to 'const char*' [-fpermissive]|

First of all, i need to say, that i am a complete noob. I am trying to make some naval combat simulation to do that i created a random letter and number generator Here's the code. By the way, what i want to achieve is to have only one variable (Guess) to be confronted with the ship places that the user specified.

char letters[]= {'A','B','C','D','E','F','G','H','I','L'};

\\ lots of code

//RandomAI
int G = rand() % 10 + 1;
int nOut = rand() % 10 + 1;
char lOut = letters[G];
string Guess = lOut + nOut;
return 0;

Upvotes: 0

Views: 14990

Answers (2)

Bizmarck
Bizmarck

Reputation: 2688

Assuming you wanted an output string like 'A7' or 'F2', one way to achieved this would be to convert everything to string (since you can't add and int and a char). For those who don't have access to C++11 and std::to_string() yet, you could use:

char letters[]= {'A','B','C','D','E','F','G','H','I','L'};
int G = std::rand() % 10;
int nOut = std::rand() % 10;
char lOut = letters[G];
std::stringstream ss;
ss << nOut;
std::string Guess = lOut + ss.str();

Upvotes: 0

AndyG
AndyG

Reputation: 41090

string Guess = lOut + nOut; adds an int and char types which does not produce a std::string. One way to address this is to create a string and then append to it:

std::string guess =  lOut + std::to_string(nOut);

This will solve your compiler error, but you still have a logic error here:

int G = rand() % 10 + 1;

rand() % 10 + 1 will produce a value between 1 and 10 inclusive. You want a number between 0 and 9 inclusive, because indices in C++ begin at 0, not 1. So drop the +1 portion:

int G = rand() % 10;

Otherwise you may accidentally attempt to access an out-of-bounds index in letters

Upvotes: 3

Related Questions