1

I am trying to divide a digit in a string which is selected by its index by 10. But instead of giving me 0.x, it provides me a different answer.

Here is an example to reproduce the error:

#include <iostream>

using namespace std;

int main()
{
    string y = "2";
    double x = y[0];
    cout << x/10.0 << endl;
}
Anonymous
  • 25
  • 1
  • 5
  • 6
    Hint: `'2' != 2`. Try: `y[0] - '0'`. – Evg Sep 14 '21 at 07:27
  • 3
    In addition to what @Evg said: [Convert char to int in C and C++](https://stackoverflow.com/questions/5029840/convert-char-to-int-in-c-and-c) which explains the meaning of `y[0] - '0'` – t.niese Sep 14 '21 at 07:36
  • `... / 10.0` will do such a conversion for you. `x` could be of type `int`. – Evg Sep 14 '21 at 07:45

1 Answers1

-1

You can't divide strings, you need to convert it to an integer.

  • OP doesn't divide strings. They divides `double`s. – Evg Sep 14 '21 at 07:31
  • @Evg OP divides a value originally of type `char`, and read in as a character, by a `double`, so @Benjamonster is not completely wrong – codeling Sep 14 '21 at 08:17
  • @codeling `x` has type `double`. `x / 10.0` is a division of two `double`s. – Evg Sep 14 '21 at 08:46