+ 3
C# basic calculator
I was studying about creating basic calculator statements and I am confused about this C# statement: int x = Convert.ToInt32(str); I understand that we are converting the input x to 32 bit integer form but what are doing with this (str) at the end? Are we converting a string to integer or back or what? Could someone please explain to me? Thank you in advance?
9 Respuestas
+ 2
Lisa Kinoti
Console.ReadLine() returns string so you enter 'exit' then it is pure string so no need to convert.
When you enter 4 then it is also a string as ReadLine() method returns only string but you need to convert 4 to integer otherwise it will be just concat.
In any programming language user input will be considered as a string.
Try this and enter 2 and 4, you will get 24
Console.Write(Console.ReadLine() + Console.ReadLine());
+ 3
ToInt32() is a funtion, it apply to a STRING and convert it to a 4 byte INTEGER. In your case, I suppose str is a variable which store some numeric in text (ASCII) format, which then transfer into number (INT32) format and store into another variable call x.
+ 2
Lisa Kinoti
Yes we are converting string "4" to integer
So that we can add 2 integer values.
+ 2
Lisa Kinoti
same like this in other languages
in python we use 'int' function
num = int(input())
In Swift we use 'Int' function
var num = Int(readLine()!)!
In JavaScript we use parseInt or Number
var num = parseInt(a, 10) or var num = Number(a)
In Java we use Integer.parseInt(str);
int num = Integer.parseInt(str);
+ 2
string str : create STRING variable call str
int x : create INTEGER variable call x
+ 1
AJ, Thank you so much!!! That makes sense. Any input I enter is considered a string even if in my mind it is a number for instance, like 4, which is why we convert to integer. Okay. So in this case, are we taking STRING str and turning it into integer and then storing it in int x so that we can add it to int y? Is this what is happening in this line?
int x = Convert.ToInt32(str)
+ 1
Aaah, yes. I get it now. Thank you so much AJ and abpatrick. I will follow you guys' profile. I appreciate you both taking the time to make sure that I understand. 😇🙏
+ 1
First, user don't know there is a special code named exit.
Second, they may not know they need to enter an integer when they see x=.
Third, they may not realize you are performing summation by only look at the result output.
Fourth, I encourage you to learn try except to deal with wrong input(non integer) by user.
0
abpatrick, Thank you for that explanation. Let me give you the scenario so you can get an idea of where I saw it. Please add anymore explanation you think will help me based on this code.
do {
Console.Write("x = ");
string str = Console.ReadLine();
if (str == "exit")
break;
int x = Convert.ToInt32(str);
Console.Write("y = ");
int y = Convert.ToInt32(Console.ReadLine());
int sum = x + y;
Console.WriteLine("Result: {0}", sum);
}
while (true);