Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string or char to int

I'm totally puzzled

string temp = "73";
int tempc0 = Convert.ToInt32(temp[0]);
int tempc1 = Convert.ToInt32(temp[1]);
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);

I would expect: 7*3=21

But then I receive: 55*51=2805

like image 861
fishmong3r Avatar asked Mar 14 '13 08:03

fishmong3r


People also ask

What does atoi () do?

Description. The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number.

What happens when you convert a char to an int?

In Java, we can convert the Char to Int using different approaches. If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character.

Can we convert char to int in C?

We can convert char to int by negating '0' (zero) character. char datatype is represented as ascii values in c programming. Ascii values are integer values if we negate the '0' character then we get the ascii of that integer digit.


2 Answers

That is the ASCII value for the character 7 and 3. If you want number representation then you can convert each character to string and then use Convert.ToString:

string temp = "73";
int tempc0 = Convert.ToInt32(temp[0].ToString());
int tempc1 = Convert.ToInt32(temp[1].ToString());
MessageBox.Show(tempc0 + "*" + tempc1 + "=" + tempc0*tempc1);
like image 64
Habib Avatar answered Oct 06 '22 00:10

Habib


55 and 51 are their locations in the ascii chart. Link to chart - http://kimsehoon.com/files/attach/images/149/759/007/ascii%281%29.png

try using int.parse

like image 40
Sayse Avatar answered Oct 06 '22 00:10

Sayse