1

I'm currently working on an assignment. Where I need to take a string, read the value at index 1 and use that value to assign a value to an integer.

    int main()  
{
   string num;
   cin>> num;
   int readval;
   readval= num.at(0);
   cout << readval;
}

the problem is whenever I print readval its never the number at the index location that i specified. for example if I wanted num.at(0)= 4 from a string like 4 1 2 3 4. I want readval to be equal to that number (in this case 4) but when I print readval it prints 52 instead of what the value is in the index. I know that 52 is the ASCII code for 4 but I don't know why its not working for me

  • 1
    You're almost there. As you've noticed, when you turn a `char` directly into a number, you get the encoded value of that character. To get a digit as a number, you need to convert it from the character encoding by subtracting the encoding value of character 0 (48 in ASCII). Eg `readval= num.at(0) - '0';`. The value of character 4 minus the value of character 0 will for all encodings allowed by C++, always be 4 – user4581301 Apr 23 '22 at 07:12
  • Being a string, `num` contains only the character code values of the character representations of the digits --- '4', not 4. You need to convert the character representation to an actual integer value. – jkb Apr 23 '22 at 07:13

2 Answers2

2

In your code the overload of the << operator taking int is used. This prints the value as an integral number instead of printing the character.

If you want to print the character, just change the type of readval to char

char readval = num.at(0);
cout << readval;

If you want to work with an int, you can use the fact that the chars for the decimal digits are "next to each other" in the ascii table in ascending order.

int readval = num.at(0) - '0';
cout << readval;
fabian
  • 80,457
  • 12
  • 86
  • 114
-2
#include <bits/stdc++.h>
using namespace std;
int main()  
{
   string num;
   cin>> num;
   int readval;
   readval= num.at(0);
   cout << readval - 48;
}
KITISH
  • 18
  • 3