doujing5846 2016-05-13 09:15
浏览 87
已采纳

reader.ReadLine()在scanner.Scan()调用后未前进

The code below reads its values from this file:

2 3

1.0 2.0 3.0

-1.0 -2.0 -3.0

And should print: [ {1 2 3}, {-1 -2 -3} ]

But instead I get this:

[{2 [31 2 3]} {0 []}] strconv.ParseFloat: parsing "3.0-1.0": invalid syntax

It seems that the reader.ReadLine() stays at the same location. Is there a simpler way to scan lines, then values inside each line?

package main

import (
    "bufio"
    "bytes"
    "fmt"
    "os"
    "strconv"
    "strings"
)

type Example struct {
    classLabel int
    attributes []float64
}

func NewExample(classLabel int, attributes []float64) *Example {
    return &Example{classLabel, attributes}
}

func readFile(path string) ([]Example, error) {

    var (
        result       []Example
        err          error
        file         *os.File
        part         []byte
        size         int
        attributeNum int
    )

    if file, err = os.Open(path); err != nil {
        return result, err
    }
    defer file.Close()

    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 0))

    if part, _, err = reader.ReadLine(); err != nil {
        return result, err
    }
    buffer.Write(part)
    newLine := buffer.String()
    fmt.Println("newLine=" + newLine)

    r := strings.NewReader(newLine)
    scanner := bufio.NewScanner(r)
    scanner.Split(bufio.ScanWords)

    if scanner.Scan() {
        size, err = strconv.Atoi(scanner.Text())
        if err != nil {
            return result, err
        }
    }
    fmt.Println("size=" + strconv.Itoa(size))

    if scanner.Scan() {
        attributeNum, err = strconv.Atoi(scanner.Text())
        if err != nil {
            return result, err
        }
    }
    fmt.Println("attributeNum=" + strconv.Itoa(attributeNum))

    result = make([]Example, size)

    var classLabel int
    var attributes []float64

    for k := 0; k < size; k++ {
        if part, _, err = reader.ReadLine(); err != nil {
            return result, err
        }
        buffer.Write(part)
        newLine := buffer.String()
        fmt.Println("newLine=" + newLine)

        r := strings.NewReader(newLine)
        scanner := bufio.NewScanner(r)
        scanner.Split(bufio.ScanWords)

        if scanner.Scan() {
            classLabel, err = strconv.Atoi(scanner.Text())
            if err != nil {
                return result, err
            }
        }
        fmt.Println("classLabel=" + strconv.Itoa(classLabel))

        for i := 0; i < attributeNum; i++ {
            var attribute float64
            if scanner.Scan() {
                attribute, err = strconv.ParseFloat(scanner.Text(), 64)
                if err != nil {
                    return result, err
                }
                attributes = append(attributes, attribute)
                fmt.Println("attribute=" + strconv.FormatFloat(attribute, 'f', -1, 64))
            }
        }
        result[k] = *NewExample(classLabel, attributes)
    }

    return result, scanner.Err()
}

func main() {
    example, err := readFile("test.txt")
    fmt.Println(example, err)
}
  • 写回答

1条回答 默认 最新

  • doutuo2829 2016-05-13 09:53
    关注

    When you do this inside the for loop:

    buffer.Write(part)
    newLine := buffer.String()
    fmt.Println("newLine=" + newLine)
    

    The next line gets appended to buffer. That is, before the loop begins, buffer contains 2 3, and then after reading 1.0 2.0 3.0, it gets appended to buffer, so the content becomes 2 31.0 2.0 3.0, which you store in newLine. That's where things start to go sideways.

    You probably want to clear the buffer before reading each new line:

    buffer.Reset()
    buffer.Write(part)
    newLine := buffer.String()
    fmt.Println("newLine=" + newLine)
    

    But then you will have further problems still, here:

        if scanner.Scan() {
            classLabel, err = strconv.Atoi(scanner.Text())
            if err != nil {
                return result, err
            }
        }
    

    Since the line contains 1.0 2.0 3.0, the strconf.Atoi is going to fail. I don't understand the purpose of this snippet, perhaps you can delete it (or comment out).

    With the above fixed, you will still have one more problem, on this line:

              attributes = append(attributes, attribute)
    

    Since attributes is never reset, it keeps growing. That is, after the first line, it will contain 1 2 3, and after the second line it will contain 1 2 3 -1 -2 -3. You could correct that by moving the declaration of attributes without the outer loop, like this:

        var attributes []float64
        for i := 0; i < attributeNum; i++ {
            var attribute float64
            if scanner.Scan() {
                attribute, err = strconv.ParseFloat(scanner.Text(), 64)
                if err != nil {
                    return result, err
                }
                attributes = append(attributes, attribute)
                fmt.Println("attribute=" + strconv.FormatFloat(attribute, 'f', -1, 64))
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog