13

My requirement is to join two characters. For example

 int main()
 {
       char c1 ='0';
       char c2 ='4';
       char c3 = c1+c2;
       cout<< c3;
 }

The value which I am expecting is 04. But what I am getting is d. I know that char is single byte. My requirement is that in the single Byte of C3 is possible to merge/join/concat the c1,c2 and store the value as 04

subbu
  • 3,229
  • 13
  • 49
  • 70
  • Please don’t tag languages that don’t relate to the question. Chars are single values, not strings. Adding them works this way. – Sami Kuhmonen Jun 25 '18 at 07:10
  • 1
    Please remove C tag. C has no cout! – Klaus Jun 25 '18 at 07:11
  • What you want is to use [*strings*](http://en.cppreference.com/w/cpp/string/basic_string). – Some programmer dude Jun 25 '18 at 07:12
  • As for the result you actually get, it's easy to understand if you know about [ASCII](http://en.cppreference.com/w/cpp/language/ascii) encoding. – Some programmer dude Jun 25 '18 at 07:13
  • Possible duplicate: [how-do-i-concatenate-const-literal-strings-in-c](https://stackoverflow.com/questions/308695/how-do-i-concatenate-const-literal-strings-in-c) – Nyque Jun 25 '18 at 07:13
  • 2
    I don't think a char can hold 0 and 4 together. Its asciii – Farhan Qasim Jun 25 '18 at 07:14
  • This will work: `int main() { char c1 ='0'; char c2 ='4'; std::string c3; c3 += c1; c3 += c2; std::cout<< c3; }` – haccks Jun 25 '18 at 07:14
  • Possible duplicate of [const char\* concatenation](https://stackoverflow.com/questions/1995053/const-char-concatenation), but not exactly... – user1810087 Jun 25 '18 at 07:27
  • 1
    I would think this question is instantly marked as duplicate, but interestingly, seems nobody asked it before, or at least I cannot find an exact duplicate... – user1810087 Jun 25 '18 at 07:29
  • Are you sure you wanted to use the `char` data type to being with? It might seem more straightforward if you used `std::string` throughout. – Tom Blodget Jun 25 '18 at 16:02
  • As you got a lot of answers, why we see no questions from you or an accept of the answer which helps you? – Klaus Jun 29 '18 at 13:40

10 Answers10

15

A char is not a string. So you can first convert the first char to a string and than add the next ones like:

int main()
{
    char c1 ='0';
    char c2 ='4';
    auto c3 = std::string(1,c1)+c2;
    std::cout<< c3;
}

What is "magic" std::string(1,c1): It uses the std::string constructor of the form: std::string::string (size_t n, char c);. So it "fills" the string with one single character of your given c1 which is the 0.

If you add chars you get the result of adding the numeric value of it which is:

int main() {
    std::cout << (int)c1 << std::endl;
    std::cout << (int)c2 << std::endl;
    std::cout << (int)c1+c2 << std::endl;
    std::cout << char(c1+c2) << std::endl;
}

The numeric value as int from 0 is 48, from 4 it is 52. Add both you get 100. And 100 is a d in ascii coding.

Klaus
  • 24,205
  • 7
  • 58
  • 113
9

What you want is called a string of characters. There are many ways to create that in C++. One way you can do it is by using the std::string class from the Standard Library:

char c1 = '0';
char c2 = '4';

std::string s; // an empty string

s += c1; // append the first character
s += c2; // append the second character

cout << s; // print all the characters out
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Galik
  • 47,303
  • 4
  • 80
  • 117
4

A char is no more than an integral type that's used by your C++ runtime to display things that humans can read.

So c1 + c2 is a instruction to add two numbers, and is an int type due to the rules of type conversions. If that's too big to fit into a char, then the assignment to c3 would have implementation-defined results.

If you want concatenation, then

std::cout << ""s + c1 + c2;

is becoming, from C++11's user defined literals, the idiomatic way of doing this. Note the suffixed s.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

Each char in C (and C++) has the length of one byte. What you are doing is adding the actual byte values:

'0' = 0x30
'4' = 0x34 
-> '0' + '4' = 0x30 + 0x34 = 0x64 = 'd'

If you want to concatenate those two you will need an array:

 int main()
   {
       char c1 ='0';
       char c2 ='4';
       char c3[3] = {c1,c2,0}; // 0 at the end to terminate the string
       cout<< c3;
       return 0;
  }

Note that doing those things with chars is C but not C++. In C++ you would use a string, just as Klaus did in his answer.

izlin
  • 2,129
  • 24
  • 30
1

Basics first

In C++ and C, a string ends with '\0' which is called null character. Presence of this null character at the end differentiates between a string and char array. Otherwise, both are contigous memory location. While calculating string.length() not counting the null character at the end is taken care.

Joining/Concatenating two characters

If you join two character using + operator, then handling the null character in both strings end will be taken care. But if you join two char with + operator and wish to see it as an string, it will not happen, because it has no null character at the end. See the example below:

char c1 = 'a';
char c2 = 'b';
string str1 = c1 + c2;
cout << str1; // print some garbled character, as it's not valid string.

string str2; // null initialization
str2 = str2 + c1 + c2;
cout << str2; // prints ab correctly.

string s1 = "Hello";
string s2 = "World";
string str3 = s1 + s2;
cout << str3; //prints Hello World correctly.

string str4 = s1 + c1; 
cout << str4; //prints Hello a correctly.
Om Sao
  • 7,064
  • 2
  • 47
  • 61
0

What you named "joining" is actually arithmetics on char types, which implicitly promotes them to int. The equivalent integer value for a character is defined by the ASCII table ('0' is 48, '4' is 52, hence 48 + 52 = 100, which finally is 'd'). You want to use std::string when concatenating textual variables via the + operator.

lubgr
  • 37,368
  • 3
  • 66
  • 117
0

Since a basic char doesn't have operator+ to concatenate itself with another char,

What you need is a representation of a string literal using std::string as suggested by others

or in , you can use string_view,

char array[2] = {'0', '4'};
std::string_view array_v(array, std::size(array));
std::cout << array_v; // prints 04
Joseph D.
  • 11,804
  • 3
  • 34
  • 67
0

You can do somthing like that:

#include <vector>
#include <iostream>

using namespace std;

int main()
{
    char a = '0';
    char b = '4';
    vector<char> c;
    c.push_back(a);
    c.push_back(b);
    cout << c.data() << endl;
    return 0;
}
Coral Kashri
  • 3,436
  • 2
  • 10
  • 22
0

Simple addition is not suitable to "combine" two characters, you won't ever be able to determine from 22 if it has been composed of 10 and 12, 11 and 11, 7 and 15 or any other combination; additionally, if order is relevant, you won't ever know if it has been 10 and 12 or 12 and 10...

Now you can combine your values in an array or std::string (if representing arbitrary 8-bit-data, you might even prefer std::array or std::vector). Another variant is doing some nice math:

combined = x * SomeFactorLargerThanAnyPossibleChar + y;

Now you can get your two values back via division and modulo calculation.

Assuming you want to encode ASCII only, 128 is sufficient; considering maximum values, you get: 127*128+127 == 127*129 == 2^14 - 1. You might see the problem with yourself, though: Results might need up to 14 bit, so your results won't fit into a simple char any more (at least on typical modern hardware, where char normally has eight bits only – there are systems around, though, with char having 16 bits...).

So you need a bigger data type for:

uint16_t combined = x * 128U + y;
//^^

Side note: if you use 256 instead, each of x and y will be placed into separate bytes of the two of uint16_t. On the other hand, if you use uint64_t and 127 as factor, you can combine up to 9 ASCII characters in one single data type. In any case, you should always use powers of two so your multiplications and divisions can be implemented as bitshifts and the modulo calculations as simple AND-operation with some appropriate mask.

Care has to be taken if you use non-ASCII characters as well: char might be signed, so to prevent unwanted effects resulting from sign extension when values being promoted to int, you need to yet apply a cast:

uint16_t combined = static_cast<uint8_t>(x) * 128U + static_cast<uint8_t>(y);
Aconcagua
  • 24,880
  • 4
  • 34
  • 59
0

https://github.com/bite-rrjo/STG-char-v2/blob/main/stg.h without external libraries it would be like this

#include "iostream"
#include "lib-cc/stg.h"
using namespace std;
int main(){
  // sum two char

  char* c1 = "0";
  char* c2 = "4";
  stg _stg;
  _stg = c1;
  _stg += c2;
  cout << _stg() << endl;
  // print '04'
 
}
bite sel
  • 1
  • 1
  • Your answer does not concatenate two characters. In fact, it seems to concatenate two strings with two characters `-b` inbetween. This is not what OP asked. – Lluís Alemany-Puig May 04 '22 at 13:48
  • Sorry I was just trying to help and my English is not that good, I made an example connecting two "char*" this might also give you the expected result without using "string" – bite sel May 06 '22 at 01:11