Skip to content
← Back to Community
how to take user input in the form of an integer
Profile icon
AaronPhilip

Please help me. This is so irritating like i just want to take two integers and add them. Instead, it takes it in the form of a string and just concatenates them.
:(

Thank you.

Answered by Coder100 [earned 5 cycles]
View Answer
Voters
Profile icon
ELIMCKNIGHT
Profile icon
OWA0001
Profile icon
ebrahimpascal
Profile icon
SophiaJones7
Profile icon
AaronPhilip
Comments
hotnewtop
Profile icon
Coder100

Hello, to do this, you will have to use the Int class:

print("Enter a number") var a = readLine()! var aint = Int(a) ?? 0 print("Enter another number") var b = readLine()! var bint = Int(b) ?? 0 var ans = aint + bint print(ans)

Note the ??. This is because if the user input was a, you wouldn't be able to convert it to a number and the variable would become null iirc.

Profile icon
AaronPhilip

@Coder100 Thank you :) it helped a lot

Profile icon
Coder100

no problem!! :D @AaronPhilip

Profile icon
PattanAhmed

@AaronPhilip Hi,
It's easy...
You just have to convert it into Int data type
Here is your code with explanation:-

// Taking input of first number and converting it into a Int Data Type print("Enter first number: ") var number = readLine()! var converting = Int(number) ?? 0 // Taking input of second number and converting it into a Int Data Type print("Enter second number: ") var number1 = readLine()! var converting1 = Int(number1) ?? 0 // Adding the both inputs var result = converting + converting1; // Printing the output print(result)

That's it
Thanks!

Hope this helps

Profile icon
AaronPhilip

@PattanAhmed
Thank you :)

Profile icon
PattanAhmed

@AaronPhilip Welcome!
Happy to help you.

Please mark my answer if that helps
Thanks!

Profile icon
GoodCoderBadBoy

I've never used swift before, but looking things up, you may need to convert the readline() output into an int. I may be totally and utterly wrong though.

print("Enter a number") var a=Int(readLine())! print("Enter another number") var b=Int(readLine())! var ans=a+b print(ans)
Profile icon
Coder100

not quite, you forgot to handle the cases when the input isn't an integer @GoodCoderBadBoy

Profile icon
GoodCoderBadBoy

@Coder100 thank you