0

I am doing a bit of competitive programming in koltin. Most of the time I used input from the console but sometimes I want to use files. Is there a way to make readln() work from a file ? The goal is to avoid writting to code doing the same thing.

From here: Reading console input in Kotlin I tries

fun <T : Closeable, R> T.useWith(block: T.() -> R): R = use { with(it, block) }

File("a.in").bufferedReader().useWith {
    File("a.out").printWriter().useWith {
        val (a, b) = readLine()!!.split(' ').map(String::toInt)
        println(a + b)
    }
}

Scanner(File("b.in")).useWith {
    PrintWriter("b.out").useWith {
        val a = nextInt()
        val b = nextInt()
        println(a + b)
    }
}

But I was not able to make it works.

Thx for any answer.

Quentin M
  • 171
  • 2
  • 11
  • Yes - see [`File.readLines()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/read-lines.html) and [`File.useLines()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/use-lines.html) – aSemy Dec 03 '22 at 18:28
  • Hi, this is not exactly what i wish to do. If I use readLines() I get a list of string however what I want is to be able to use readln() for example and each time I make this call a new line of my file is read. – Quentin M Dec 03 '22 at 18:35
  • Ah okay. You can [convert a list into an iterable](https://kotlinlang.org/docs/iterators.html), and then use [`.next()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-iterator/next.html) - [Kotlin Playground example](https://pl.kotl.in/K2tWKj7cR) – aSemy Dec 03 '22 at 19:28

1 Answers1

0

Thx to @aSemy comment I make it works:

val seq = File("./src/ts1_input.txt").readLines().listIterator() 

fun readString() = seq.next() // readln()
aSemy
  • 5,485
  • 2
  • 25
  • 51
Quentin M
  • 171
  • 2
  • 11