-1

I have this string str . I want to Multiply value of each position of string with 7 or any value. First I used string Function str.at() and stored in a new char type variable, but when i multiplied the index 0 value: 9 with 7 it's giving me 399 instead of 63. I have also tried this without a string function, like this: char s = str[0]; and then multiplied s with 7 but i'm still not getting the correct answer.

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string str = "9958721";
    char s = str[0];
    cout << s * 7;

    cout << "\nPROGRAM ENDED...";
    return 0;
}
Hassan
  • 41
  • 8

1 Answers1

2

That's because '9' ASCII code is 57. See

To get the expected result use something like the following

string str = "9958721";
char s = str[0];
cout << 7 * (static_cast<int>(s) - static_cast<int>('0'));

to subtract the equivalent ASCII value of zero. Note that they are ordered.

And see Why is "using namespace std;" considered bad practice?

asmmo
  • 6,922
  • 1
  • 11
  • 25