1

I'm writing a code to add the first and last integer of a number. But the output results in binary instead of integer. //Code

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

int main() {
    int t, n;
    cin >> t;
    for (int i = 0; i < t; i++) {
        cin>> n;
        string s = to_string(n);
        char first = s[0];
        char last = s[s.length() - 1];
        int a = first;
        int b = last;
        cout << first + last;
    }
    return 0;
}

output code

/tmp/ujHkZRfwZL.o
1
1234
101
11
  • 1
    Read about the ASCII representation. For example, the character '9' has a decimal value of 57, not 9 like you might expect. Commented May 3, 2021 at 19:25
  • 1
    But the output results in binary instead of integer; Please provide the output Commented May 3, 2021 at 19:26
  • i've updated the output Commented May 3, 2021 at 19:30
  • and it's not giving the ascii conversation but in binary Commented May 3, 2021 at 19:31
  • 1
    If the input is 1234 then your program, as shown, would do '1' + '4' which with ASCII will be 49 + 51 which indeed is 101. Not binary, you just haven't tested with anything else. Try e.g. 12345 instead, and the result will be 102. Commented May 3, 2021 at 19:33

1 Answer 1

2

You should at least write

    int a = first - '0';
    int b = last - '0';
    cout << a + b;
Sign up to request clarification or add additional context in comments.

4 Comments

It should be noted that this subtraction "trick" is only guaranteed to work with digit characters, as it's specified in the C++ specification. There are other encodings than ASCII still in active use, where it's not possible to do this on letter characters.
thankyou that i worked i was adding first and last instead of a and b. thankyou soo much
can you explain me the use of - '0' in this line why we used it
@AmnRwt If for example the object last contains the character '4' then '4' - '0' results in integer 4. Characters that correspond to digits are follow each other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.