Text from users is full of surprises, so every conversion can fail.
What to build
A program that converts words to numbers and reports the ones that are not numbers.
Requirements
- Read n, then n words (they may be any text).
- For each word print
ok Nif it is a whole number (a leading minus sign is allowed) orbad WORDif it is not. - Finally print
valid: V, bad: B, sum: Swith the count of valid words, the count of bad words and the sum of the valid numbers.
Input
Line 1: n. Then n words separated by spaces or new lines.
Output
n lines and a summary line.
Constraints
1 ≤ n ≤ 50; words have at most 12 characters; valid numbers are between -100000 and 100000.
Example
Input:
4
12 abc -5 7x
Output:
ok 12
bad abc
ok -5
bad 7x
valid: 2, bad: 2, sum: 7
Why it works
Atoi returns an error for any word that is not a whole number, so the program can handle bad input without crashing and without treating it as 0.
Examples
Example 1 · Input
4 12 abc -5 7x
Expected output
ok 12 bad abc ok -5 bad 7x valid: 2, bad: 2, sum: 7
Example 2 · Input
3 0 99999 -100000
Expected output
ok 0 ok 99999 ok -100000 valid: 3, bad: 0, sum: -1
Hints
Hint 1
Use strconv.Atoi(token) and check err != nil.
Hint 2
Count the valid numbers, the bad words, and add the valid ones.
Solution
Show one correct solution (try it yourself first)
package main
import (
"fmt"
"strconv"
)
func main() {
var n int
fmt.Scan(&n)
valid, bad, sum := 0, 0, 0
for i := 0; i < n; i++ {
var w string
fmt.Scan(&w)
v, err := strconv.Atoi(w)
if err != nil {
fmt.Println("bad", w)
bad++
continue
}
fmt.Println("ok", v)
valid++
sum += v
}
fmt.Printf("valid: %d, bad: %d, sum: %d\n", valid, bad, sum)
}