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
CodePudding user response:
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;
CodePudding user response:
#include <bits/stdc .h>
using namespace std;
int main()
{
string num;
cin>> num;
int readval;
readval= num.at(0);
cout << readval - 48;
}