i have a console input
b a
c b
c a
c c
c F
and i am reading it like following:
wtf:=make([]string,5)
reader := bufio.NewReader(os.Stdin)
for i:=0;i<5;i++{
line, _ := reader.ReadString('
')
wtf[i]=line
}
But, i am not reading the last line because it has no ' ' so i've added the following code
var kek string
kek=""
for i:=0;i<2;i++{
line, _:=reader.ReadString(' ')
kek+=line
}
Now in wtf
are stored first 4 lines and in kek
is the last one. Now i want kek
to be 4-th element of wtf
. As i can understand, wtf
is a slice, so there should be no problem for doing this:
wtf[5-1]=kek
BUT that's not working, i am getting this output for wtf
:
[
b a
c b
c a
c F
]
And if i check wtf
's len it would be still 5!
P.S. Total number of lines and symbols to read in it are given, so digits 5 and 2 could be replaced for n and m.
The line:
kek=""
That line is unnecessary, kek is already an empty string because an empty string is the nil value for string.
Since you have not shown where your second block of code fits in the first block, I cannot comment on how you got your wrong result.
Anyway, ReadString will read in the last line regardless of whether there is a newline character. This will work:
wtf := make([]string)
reader := bufio.NewReader(os.Stdin)
for {
line, err := reader.ReadString('
')
wtf = append(wtf, line)
if err != nil {
break;
}
}
Use the bufio.Scanner instead of bufio.Reader. The bufio.Scanner type was added in Go 1.1 to simplify tasks that are needlessly complex with bufio.Reader.
var wtf []string
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
wtf = append(wtf, s.Text())
}
if err := s.Err(); err != nil {
// handle error
}
The wtf
elements in the question include the at the end of each line. The code in this answer does not.