英文:
Why does this go code ignore the second inputed number?
问题
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("输入字符串=>")
a1, _ := reader.ReadString('\n')
a1 = strings.Replace(a1, "\n", "", -1)
b1 := strings.Split(a1, " ")
var b2 [2]int
for i := 0; i < 2; i++ {
b2[i], _ = strconv.Atoi(b1[i])
}
fmt.Println(b2[0] + b2[1])
}
这段代码产生以下输出:
输入字符串=> 5 6
11
但在JetBrains Goland中,它产生了正确的输出。
英文:
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter String=>")
a1, _ := reader.ReadString('\n')
a1 = strings.Replace(a1, "\n", "", -1)
b1 := strings.Split(a1, " ")
var b2 [2]int
for i := 0; i < 2 ; i++ {
b2[i], _ = strconv.Atoi(b1[i])
}
fmt.Println(b2[0] + b2[1])
}
This code produces the following output
Enter String=> 5 6
5
But in Jetbrains Goland it produces the correct output.
答案1
得分: 2
Windows使用CRLF (\r\n
)作为换行符。使用strings.TrimSpace而不是Replace。
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("输入字符串=>")
a1, _ := reader.ReadString('\n')
a1 = strings.TrimSpace(a1)
b1 := strings.Split(a1, " ")
var b2 [2]int
for i := 0; i < 2; i++ {
b2[i], _ = strconv.Atoi(b1[i])
}
fmt.Println(b2[0] + b2[1])
}
或者,使用strings.Fields代替Replace和Split。
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("输入字符串=>")
a1, _ := reader.ReadString('\n')
b1 := strings.Fields(a1)
var b2 [2]int
for i := 0; i < 2; i++ {
b2[i], _ = strconv.Atoi(b1[i])
}
fmt.Println(b2[0] + b2[1])
}
英文:
Windows terminates lines with CRLF (\r\n
). Use strings.TrimSpace, not Replace.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter String=>")
a1, _ := reader.ReadString('\n')
a1 = strings.TrimSpace(a1)
b1 := strings.Split(a1, " ")
var b2 [2]int
for i := 0; i < 2 ; i++ {
b2[i], _ = strconv.Atoi(b1[i])
}
fmt.Println(b2[0] + b2[1])
}
Or, use strings.Fields instead of Replace and Split.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter String=>")
a1, _ := reader.ReadString('\n')
b1 := strings.Fields(a1)
var b2 [2]int
for i := 0; i < 2; i++ {
b2[i], _ = strconv.Atoi(b1[i])
}
fmt.Println(b2[0] + b2[1])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论