当前位置:网站首页>os. When the command line parameter in args[1:] is empty, the internal statement will not be executed

os. When the command line parameter in args[1:] is empty, the internal statement will not be executed

2022-06-22 23:23:00 Jimmy_ jimi

Problem description

When the value entered on the command line is null , Not execute else Statement block after .

func qualityTran() {
    
	for _,v := range os.Args[1:]{
    
		// If it's not empty , Direct conversion to original value 
		if v !=""{
    
			a,_ := strconv.Atoi(v)
			fmt.Println(tran(a))
			//input.Scan()
		}else {
    
			fmt.Println("1")
			// If it is empty, it is read from the standard input 
			fmt.Println("please input a num:")
			input := bufio.NewScanner(os.Stdin)
			input.Scan()
			a :=input.Text()
			b,_ := strconv.Atoi(a)
			fmt.Println(tran(b))
		}
	}
}

Cause analysis :

During the actual program execution ,for The cycle ends directly , Will not enter if Sentence judgment .


Solution :

func qualityTran() {
    
	flag :=0
	for _,v := range os.Args[1:]{
    
		// If it's not empty , Direct conversion to original value 
		if v !=""{
    
			a,_ := strconv.Atoi(v)
			fmt.Println(tran(a))
			//input.Scan()
			flag =1
		}
	}
	if flag ==0 {
    
		// If it is empty, it is read from the standard input 
		fmt.Println("please input a num:")
		input := bufio.NewScanner(os.Stdin)
		input.Scan()
		a :=input.Text()
		b,_ := strconv.Atoi(a)
		fmt.Println(tran(b))
	}
}
原网站

版权声明
本文为[Jimmy_ jimi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222053148374.html