bobaloogie
bobaloogie

Reputation: 45

Convert 2 character into a string

I need to convert two numbers from a 2 dimensional array into characters, and then make those two characters one string. for example if i have [0][0], the first number in the array corresponds to a letter character which should be 'A' in this example and the second number corresponds to a number character which should be '1' in this example. I am doing this with the following code:

int i, j;
char c, c2;
for(i = 0; i < 3; i++){
    for(j = 0; j < 3; j++){
       c = i + 'A';
       c2 = j + '1';

This gives me the characters I need but then I need to convert these two characters into one string and I'm not quite sure how to do that. I tried string s = c + c2 but this gives an error for converting trying to convert an int to string.

Upvotes: 0

Views: 241

Answers (2)

Ankit Mishra
Ankit Mishra

Reputation: 590

This will make 1 single string of all characters if you one to store separately you can use string array to store them.

int i, j;
char c, c2;
string s="";
for(i = 0; i < 3; i++)
{
    for(j = 0; j < 3; j++)
    {
      c = i + 'A';
      c2 = j + '1';
       s=s+c;
       s=s+c2;
    }
}

Upvotes: 0

Aplet123
Aplet123

Reputation: 35560

You can construct a string with an initializer list:

string s = {c, c2};

Upvotes: 7

Related Questions