0

I want to add the first digit of a string 111 to the integer x = 0 so that it equals

x = 0 + 1 = 1

The following code takes the character 1 instead of the integer 1:

int x = 0;
string str = "111";
x += str[1];

std::stoi did not work either:

x += std::stoi(str[1]);

Dnk8000
  • 3
  • 3
  • `stoi` didn't work because `stoi` according to the cpp reference takes a `string` as a parameter, not a `char`. `str[1]` is a single character, not a `string`. – MPops Apr 07 '20 at 17:44

1 Answers1

2

The simple way to convert a digit to an integer is to substract '0' from it.

x += str[0] - '0';

This works because the encodings of the decimal digits are guaranteed to be continuous. So subtracting the lowest digit gives you the digit value.

Your other error is that the first character of a string is str[0] not str[1].

john
  • 85,011
  • 4
  • 57
  • 81