How do I deal with garbage input in Go? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How do I deal with garbage input in Go?

What if I want an integer but they put something like "h" or "jfkdsjfiopw fiowej fopis"? How do I deal with it?

9th May 2021, 1:33 AM
Koloroj
3 Answers
+ 2
NEZ Well, I tested something out, and apparently, inputting a character or a string will end up wih zero, while inputting a float will end up with the program taking only the number before it. And if the program loops (like this one I made for testing): package main import "fmt" func main(){ for true{ var sample int fmt.Println("Input an integer.") fmt.Scanln(&sample) fmt.Println("Your number is: ", sample, ".") if sample==0{ return } } } This program skips user input the next time and instead uses the digits that come after the decimal point. It's cool and weird. I guess I can use other parts of Go to get around this zero-defaulting thing.
9th May 2021, 3:58 AM
Koloroj
+ 1
NEZ I didn't find it when I searched that in DuckDuckGo.
9th May 2021, 3:01 AM
Koloroj
+ 1
NEZ The thread you've mentioned is completely unrelated. Garbage collection is how Go manages memory for your program. Koloroj Thanks for sharing your find. I found that not just a dot, Go will skip atmost 1 character when parsing another number from the input. For example, your program will parse both 100 and 200 from the following inputs """ 100.200 100;200 100r200 """ But this will fail "100..200". The weirdest part is that "100 200" (1 space) does not work. Whereas space separated input is accepted in most languages like C, C++ and Java Considering the many similarities I found in Go and C while learning Go, I thouht it would be like C where when the input fails, the input scanner just stops at the current character and keep reconsuming it till it is parsed into a suitable type.
9th May 2021, 5:06 AM
XXX
XXX - avatar