Hi everybody. Hope you are all well in the new year.

I'm having trouble with joining two chars and displaying the output. For example
Any clues as to how to do this? Thanks so much.

#include <iostream>
#include <string>

using namespace std;

int main();
{
char a = 'x';
char b = 'y';

//the below gives me a funny symbol.  Probably cos it's seeing the binary value of the chars.
cout << a + b << endl;

//I tried turning them to strings like this. But it doesn't work.  I get an errory like;
// cannot covert std string to char*;  
string c,d;

c = (string)a;
d = (string)b;

strcat(c,d)
cout << c << endl; 

}

Recommended Answers

All 4 Replies

The issue is that char is an integer type, so a+b will add the ASCII values of a and b, which gives weird output. Converting them to strings works fine, except that strcat uses char* c-style strings and you used std::string c++ style strings.

Here you have 2 options:

Option A: C-Style strings

char result[3];//a,b,NULL
result[0]=a;
result[1]=b;
result[2]=0;//null terminate

cout<<result<<endl;

Option B: C++-Style strings

string c=(string)a;
string d=(string)b;

cout<<c+d<<endl;

For obvious reasons the C++ style is usually considered better. However the c-style version likely takes less memory. Both should work though.

Hope this helps!

a+b adds the two ascii values. Look at any ascii table and you will see that 'a' == 97 and 'b' == 98, so a+b = 97+98 = 195. Now look again at that ascii table and find the character whose ascii value is 195.

What you want to do is to save them in an array of characters

char array[3]; // room for 2 characters
array[0] = 'a';
array[1] = 'b';
array[2] = '\0'; // string null-terminator

cout << array << '\n';

[edit] What ^^^ he said too :)

You can also use the stringstream class - Click Here

Here's a small example:

#include <sstream>
#include <iostream>
#include <string>
using namespace std;

int main(){ 
    char a = 'a';
    char b = 'b';

    stringstream ss; 
    ss<<a<<b; //adds both chars to the stringstream

    string concat = ss.str(); //you can get a string output of the stringstream

    cout<<ss.str()<<endl; //you can just output it, and see the result

    return 0;
}

Thanks very much everyone. These examples will be useful in several ways. This explains why I'm getting funny characters then.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.