golang:逐行读取int字符串的文本文件 [英] golang: read text file line by line of int strings

查看:66
本文介绍了golang:逐行读取int字符串的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个包含整数列表作为字符串的输入文件

  10.. 

我选择逐行阅读 ReadString('\ n')方法

以下代码

 行,错误:= inputReader.ReadString('\ n')lineStr:=字符串(行) 

控制台输出(长度和值)

  lineStr%v 4lineStr%v 10 

lineStr的长度为"4",可能是由于符文编码.

然后我尝试了几种方法将其转换为简单的整数,但没有成功.

Ex1

  num,_:= strconv.ParseUint(lineStr,0,64) 

输出数字0(应为10)

Ex2

  num,_:= strconv.Atoi(lineStr) 

输出数字0(应为10)

Ex3

  num,_:= strconv.Atoi("10") 

输出10(确定)

Ex4

  num,_:= strconv.ParseUint("10",0,64) 

输出10(确定)

字面意义上的字符串可以,但是文件中的字符串不起作用,这是怎么回事?

预先感谢

解决方案

从文档:"ReadString读取直到输入中第一次出现delim为止,返回一个字符串,其中包含直到定界符(包括定界符)的数据."

因此,我建议您使用扫描仪,该扫描仪可以像您期望的那样处理这种情况:

  scanner:= bufio.NewScanner(文件)用于扫描仪.Scan(){lineStr:= Scanner.Text()num,_:= strconv.Atoi(lineStr)fmt.Println(lineStr,num)} 

I am dealing with an input file containing a list of integers as a string

10
..

I have choosen to read it line by line with ReadString('\n') method

The following code

line, error := inputReader.ReadString('\n')
lineStr := string(line)

console output (length and value)

lineStr %v 4
lineStr %v 10

lineStr as a length of "4", maybe because of rune encoding.

Then I have tried several way to convert it to simple integer but with no success.

Ex1

num, _ := strconv.ParseUint(lineStr, 0, 64)

ouputs a num of 0 (should be 10)

Ex2

num, _ := strconv.Atoi(lineStr)

ouputs a num of 0 (should be 10)

Ex3

num, _ := strconv.Atoi("10")

ouputs a num of 10 (ok)

Ex4

num, _ := strconv.ParseUint("10", 0, 64)

ouputs a num of 10 (ok)

string in literal are ok but string from file do not work, what is wrong ?

thanks in advance

解决方案

From the documentation: "ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter."

Because of this, i suggest you use a scanner, which handles this case like you would expect:

scanner := bufio.NewScanner(file)
for scanner.Scan() {
    lineStr := scanner.Text()
    num, _ := strconv.Atoi(lineStr)
    fmt.Println(lineStr, num)
}

这篇关于golang:逐行读取int字符串的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆