+ 1

CMD freezes when char or string is passed into var currentamt

I'm trying to add a failsafe if else statement if a accidently string or char is passed into variable currentamt. But if a char or string is passed into currentamt through currentamt = Convert.toint32(console.readline()); Then the commandline freezes and this is my debugging error "Input string was not in a correct format". How do i fix this I was like ok? So I tried to do currentamt = Console.Readline(); and then complains that it cannot implicitly convert type string to int. But currentamt is a var?

19th Dec 2021, 4:03 PM
Caleb Nielsen
Caleb Nielsen - avatar
6 Answers
+ 2
// try this Int32.TryParse(Console.ReadLine(), out currentamt);
19th Dec 2021, 4:30 PM
SoloProg
SoloProg - avatar
+ 4
Can you please link your code? You could use TryParse() and maybe exception handling. https://www.tutorialspoint.com/chash-int-tryparse-method
19th Dec 2021, 4:23 PM
Lisa
Lisa - avatar
+ 2
I think var currentamt would be int as it is initialized with 0.
19th Dec 2021, 4:31 PM
Lisa
Lisa - avatar
+ 2
Ok i put the Int32.Tryparse(Console.Readline(), out currentamt) into the if statement and that worked thanks bud
19th Dec 2021, 4:43 PM
Caleb Nielsen
Caleb Nielsen - avatar
+ 2
To improve your conditional statements: answer = Console.ReadLine().ToUpper().Trim(); if (answer == "YES" || answer == "Y") {...}
19th Dec 2021, 4:52 PM
SoloProg
SoloProg - avatar
19th Dec 2021, 4:30 PM
Caleb Nielsen
Caleb Nielsen - avatar