1

This is the code I wrote for finding the sum of any integer that is inside a string. (for example, hello56 should give answer 11)

BUT,

#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <algorithm>

using namespace std;

#define ll long long
#define ull unsigned long long

int main() {
    ios_base::sync_with_stdio(false);
    int t;
    int sum;
    cin >> t;
    while (t--) {
        string s;
        cin >> s;
        sum = 0;
        for (int i = 0; i < s.size(); i++) {
            if (isdigit(s[i])) {
                sum = sum + s[i];
            }
        }
        cout << sum << "\n";
    }
    return 0;
}

but this code adds 48 for every integer in the string (for hello56 it gives 107) and if I change sum=sum+s[i]; to sum=sum+s[i]-48; it works, WHY?

chqrlie
  • 131,814
  • 10
  • 121
  • 189

4 Answers4

1

Program is printing the ascii value of 5+6.

'5'=53
'6'=54
so 53 + 54 = 107.

In order to convert char to number you can use s[i]-'0'.

'5' - '0' = 5
'6' - '0' = 6
0

48 is the ASCII value of character 0: sum = sum + s[i] - '0'; computes the sum of the digits.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
0

You seem to be mixing up integers and characters, as you can see in following code excerpt:

   int sum;
   ...
        string s;
   ...
                sum = sum + s[i];

A string consists of characters, which can be letters, digits or punctuation marks. You are taking the sum of an integer and a character. When doing that, the integer "translation" of the character is taken, which is better known as the ASCII code.

The ASCII codes for the digits are the following:

character  ASCII code
      '0'          48
      '1'          49
      '2'          50
      '3'          51
      '4'          52
      '5'          53
      '6'          54
      '7'          55
      '8'          56
      '9'          57

As you can see, you get the following interpretation:

ASCII_Code(character) = meaning(character) + 48

When you are doing sum = sum + s[i], then s[i] is the same as ASCII_Code(i), which explains your problem.

Therefore, in order to know the meaning of a character, you can do the following:

meaning(character) = ASCII_Code(character) - 48              // or clearer:
meaning(character) = ASCII_Code(character) - ASCII_Code('0')
Dominique
  • 16,450
  • 15
  • 56
  • 112
  • Re: "or clearer:" -- better is "better, because portable:". The C and C++ standards require that the characters `'0'..'9'` must be contiguous and increasing. So for **every** valid character encoding (not just ASCII), `character - '0'` gives the numeric value that the (digit) character represents. – Pete Becker May 24 '21 at 14:39
  • @PeteBecker: you are free to edit my answer accordingly. I was just using `ASCII_Code()` as this is the mostly used encoding. – Dominique May 24 '21 at 16:08
0

In all standardised character sets the character '0' (which prints as a zero on screen) has a non-zero numeric value.

There are a number of reasons for this - including the convention (used in C) of using a character with numeric value of 0 being used to mark the end of a string of characters. This convention, if '0' had a numeric value of zero, mean that it would not be possible to represent a value like 100 as a string (every digit '0' would mark the end of the string).

In character sets compatible with ASCII, '0' has a numeric value of 48. There are standardised character sets with '0' having a different numeric value.

Fortunately, in all standardised character sets, the arabic numerals ('0', '1', .... '9') are a contiguous set so, if x is a character containing an arabic numeral, x - '0' will convert x to its corresponding numeric value (e.g. '0' - '0' gives an integral value of 0, '1' - '0' is 1, etc).

So, when examining digits presented in a string, it is necessary to subtract '0' from each to convert it to its numeric value. For example, adding the characters of "12" as 10*'1' + '2' will (for an ASCII character set) give a value of 540, but subtracting '0' from each character (i.e. 10*('1' - '0') + ('2' - '0') will give 12.

This can be demonstrated in the following code snippet.

#include <iostream>

int main()
{
      char digit = '0';

      std::cout << digit << '\n';          // will print 0 (followed by newline)
      std::cout << (int)digit << '\n';     //  for an ASCII character set will print 48

      std::string test = "12";

      int incorrect_sum = 0;
      int correct_sum = 0;

      for (const auto c : test)
      {
           incorrect_sum *= 10;
           incorrect_sum += c;

           correct_sum *= 10;
           correct_sum += c - '0';    // note the correction here
      }

      std::cout << incorrect_sum << ' ' << correct_sum << '\n';  // will print 540 and 12

}
Peter
  • 35,646
  • 4
  • 32
  • 74