-1

I am trying to concatenate the characters of a string but getting numerical value(s) instead. Why's that so?

C#

using System;

namespace std {
    class Program {
        static void Main(string[] args) {
            string n = "helloWorld!";
            Console.WriteLine(n[0] + n[1] + n[2] + n[3] + n[4] + n[5]);
        }
    } 
}

C++

#include <iostream>
using namespace std;

int main() {
    string x = "helloWorld!";
    cout << x[0] + x[1] + x[2] + x[3] + x[4] + x[5] << endl;
    return 0;
}

Output(Both languages) -

619

Expected Output -

helloW
Naitik
  • 55
  • 1
  • 8
  • Well, you're also having a type overflow (byte or char can't go beyond 255 = 0xff) and an implicit cast into a bigger type (int has maximum value of 0xffffffff), because 619 is not representable with char/byte. You can however group "hell", "oWor", etc from array of string with 4 char (4*32bits) into an array of int (1*32 bits) and display those numbers. – Soleil Dec 14 '20 at 04:34
  • @Soleil-MathieuPrévot What if I use chars instead of integers? I know that would be confusing but is it possible? – Naitik Dec 16 '20 at 14:23
  • Well, it seems you're trying to use a python syntax in a c++/c# context (it does something else). Try this to convert an array of bytes into another type (int, long, long long): `template T ToType(const byte* x) { T value{}; for (int i = 0; i < sizeof T; i++) value += ((long)x[i] & 0xffL) << 8 * i; return value; }`. You use it this way: `ToType(charArray)` with `unsigned char* charArray[someSize]` – Soleil Dec 16 '20 at 14:35
  • In general, as in mathematics, you want to know what exactly does the + function. Its definition can be different than the usual one (from Peano's arithmetic), it is not abelian in program languages, in python it concatenates the arguments when they are string, here it's doing a non commutative addition. – Soleil Dec 16 '20 at 14:44

1 Answers1

3

All x[i] are chars. A Char stores a numerical value that represents a character depending on the encoding you're using. When you do x[i] + x[j], you're not concatenating them, you're simply adding their numerical values.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Gary Strivin'
  • 908
  • 7
  • 20