从stdin中读取行,直到某个字符 [英] Read lines from stdin until certain character

查看:113
本文介绍了从stdin中读取行,直到某个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学Go。

我的程序应该读取stdin的数据,直到我输入一个句点。

 包主

导入(

os
fmt
bufio



func main(){

in:= bufio.NewReader(os.Stdin)
input:=

用于输入!=。 {
input,err:= in.ReadString('\ n')
if err!= nil {
panic(err)
}
}

如何修改我的for循环,当我输入一个点时停止程序?



我试图用for语句实现while循环,我的方法有什么问题,条件是错误的,还是ReadString与我的数据混淆? / b>

解决方案


...是ReadString搞乱了我的数据吗?


不,它不是。它正在阅读下一个'\ n'。这意味着只有一个点的行将有数据。\\\
。\r\\\
取决于操作系统。



要删除行尾,我会执行 input = strings.TrimRight(input, \r\\\


I'm learning Go.

My program should read data from stdin until I enter a line with a single period.

package main

import (

  "os"
  "fmt"
  "bufio"

)

func main(){

  in    := bufio.NewReader(os.Stdin)
  input := ""

  for input != "." {
    input, err := in.ReadString('\n')
    if err != nil {
      panic(err)
    }
  }
}

How I should modify my for loop, to stop the program when I enter a single dot ?

I tried to implement a while loop with the for statement, is there something wrong with my approach, is the condition wrong, or is ReadString messing with my data ?

解决方案

... is ReadString messing with my data?

No, it isn't. It is reading up to the next '\n'. That means that a line with only a dot on it will have the data ".\n" or ".\r\n" depending on the operating system.

To remove line endings, I would do input = strings.TrimRight(input, "\r\n")

这篇关于从stdin中读取行,直到某个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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