How do I handle input and output?

Modified on Tue, 28 May at 3:53 PM

Your program should always read/write to STDIN/STDOUT. Depending on the programming language, this can be done in multiple ways. 


Here follows some examples how to handle input and output in Kattis.


APL

:Trap 1005
    :Repeat
        data←⍞
        ⎕←data
    :End
:End

C


#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char str[1000];
    while (fgets(str, 1000, stdin)) { //Or scanf
        printf("%s", &str);
    }
    return 0;
}



C++

#include <iostream>
#include <algorithm>

int main(void) {
    long long data;
    while (std::cin >> data)
        std::cout << data << std::endl;
    return 0;
}

C#

using System;

public class Program {
    public static void Main() {
        string line;
        while ((line = Console.ReadLine()) != null) {
            Console.WriteLine(line);
        }
    }

Java

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
/* Note that scanner can be very slow on large inputs. Consider using a buffered reader such as the KattIO library if the problem has large inputs*/ 
        while (sc.hasNextLong()) {
            long data = sc.nextLong();
            System.out.println(data);
        }
    }

}

JavaScript on Node.js

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.on('line', (line) => {
    var data = parseInt(line);
    console.log(data);
});

JavaScript on SpiderMonkey

var line;

while (line = readline()) {
    var data = parseInt(line);
    print(data);
}

PHP

<?php

while (fscanf(STDIN, '%s', $data) === 1) {
    fprintf(STDOUT, "%s\n", $data);
}

Python 3:

#! /usr/bin/python3
import sys
 
for line in sys.stdin:
    data = int(line)
    print(data)

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article