C++ question about a code with strings

This code is supposed to split Num into 3-digit segments and assign those segments to Num2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include<string>

using namespace std;

int main(){
    string Num, Num2;

    cin >> Num;

    for (int i = 3; i < Num.length() + 3; i += 3){
        Num2 = Num[Num.length() - i] + Num[Num.length() - i + 1] + Num[Num.length() - i + 2]
        cout << Num[Num.length() - i] << Num[Num.length() - i + 1] << Num[Num.length() - i + 2] << endl;
        cout << Num2 << endl;
    }

return 0;
}


input:
123456

output:
456
ƒ
123
û

Question:
why is Num2 being set to ƒ and û instead of 456 and 123?

ƒ is Alt+159
û is Alt+150
This is meant to only work for inputs whose length is a multiple of 3.
From ASCII table:
Dec Chr
 49  1
 50  2
 51  3
 52  4
 53  5
 54  6
150  û
159  ƒ

49+50+51 == 150
52+53+54 == 159


There is no operator+ for char. The nearest match is operator+ for integers. Therefore, each char is implicitly converted into integers before the addition and the result is integer.

There is no assignment of integer into std::string either, but there is string::operator= that takes a char. Therefore, the integer is converted into char before assignment.


Perhaps you should append characters to Num2?
Topic archived. No new replies allowed.