加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang从stdin中读取一行

发布时间:2020-12-16 18:53:43 所属栏目:大数据 来源:网络整理
导读:? 本文转自 life 的 leanote 博客 : http://leanote.com/blog/view/531706971a91084358000000 fmt.Scanln()不是读取一行,而是遇到换行就停止, Scanln is similar to Scan,but stops scanning at a newline and after the final item there must be a newline

?本文转自lifeleanote博客:http://leanote.com/blog/view/531706971a91084358000000

fmt.Scanln()不是读取一行,而是遇到换行就停止,

Scanln is similar to Scan,but stops scanning at a newline and after the final item there must be a newline or EOF.

举个例子:

vari,j,kint
fmt.Scanln(&i,&j,&k)
fmt.Println(i,k)

输入1,2 回车后程序结束. 如果换成fmt.Scan()还会让输入的.

使用stdin与reader联合起来读一行数据:

reader:=bufio.NewReader(os.Stdin)
strBytes,hasMore,err:=reader.ReadLine()

但bufio与fmt.Scan()一起用时会有错误,可能是bufio的问题,bufio多读,导致fmt.Scan()不能读

还是自己写个方法读一行:

//得到一行
funcScanLine()string{
	varcbyte
	varerrerror
	varb[]byte
	for;err==nil;{
		_,err=fmt.Scanf("%c",&c)
		
		ifc!='n'{
			b=append(b,c)
		}else{
			break;
		}
	}
	
	returnstring(b)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读