Himura Da Battosuai Himura Da Battosuai - 1 year ago 74
C# Question

Converting string to int in c#, and having a logical issue

I want to take two string input from user in c#, and than convert them to integer by their position in array and then add them. My code is the one below.

string a = Console.ReadLine();
string b = Console.ReadLine();
int i,c,d,j;
for (i=a.Length-1;i>=0;i--)
c = Convert.ToInt32(a[i]);
d = Convert.ToInt32(b[i]);
j = c + d;
Console.WriteLine("{0} ",j);

This code is showing wrong output such as "99 99" for input "12 21".
I wanted to add c+d then put the sum in j. Ultimately I want to write a code for big sum problem. Where I am making mistakes?
Forgive me for any wrong code, question format, I am new to both c# and stack overflow.

Answer Source

When you use the string (array) like a[i] you are not getting what you want...

The way you are referencing the string is the problem. Even though “a” is a string... when you reference it like c = Convert.ToInt32(a[i]); a[i] is going to return something else. You want to get a[i]’s value.

c = Convert.ToInt32(a[i].ToString());
d = Convert.ToInt32(b[i].ToString());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download