OJ练习的输入输出

Posted by Xsp on January 13, 2018

标准输入输出(POJ)

Java

POJ中,提交java 代码默认保存到了一个Main.java的文件,所以代码里的类名也需要命名为Main,大概这个ACM中默认的约定。

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        //...
        in.close(); //关闭流并释放,这个很重要,否则是没有输出的
        out.close(); //关闭流并释放
    }
}

另外在输入的时候可以对 System.in 再进行一层包装,因为BufferedInputStream 代表使用缓冲区,防止每次读取操作时都需要进行实际写操作,这样在数据量较大的时候速度较快。(这里不太懂,待再看。)

Scanner in = new Scanner (new BufferedInputStream(System.in));
// 读一个整数
int n = sc.nextInt();
// 读一个字符串
String s = sc.next();
// 读一个浮点数
double t = sc.nextDouble();
// 读一整行
String s = sc.nextLine();

// 多行输入
while(in.hasNextInt())
while(in.hasNext())
while(in.nextLine())
while(in.hasNextDouble())
// ...

// 格式化输出,
System.out.format("%.2f", 1.1).println(); // 1.10

DecimalFormat fd = new DecimalFormat("00000.00000");
System.out.println(fd.format(-1234.567)); // -01234.56700

// 这个不太懂,再看吧
DecimalFormat fd1 = new DecimalFormat("#.#");
System.out.println(fd1.format(-1234.567));  // -1234.6

// 高精度,待再看
int a = 123;
BigInteger x;  
x = BigInteger.valueOf(a);   

C/C++

// 读入整数
scanf("%d", &n);
cin >> n;
// 读入字符串
scanf("%s", s);
cin >> s;
// 读入浮点数
scanf("%lf", &t);
cin >> t;
// 读入一行
gets(s);
cin.getline(char* s, streamsize n);
getline (istream& is, string& str);

读写文件(codejam)

需要注意的是,下面的代码中,读入一个int后,需要跳过一个换行符?

Java

与上面的类似只是将System.outSystem.in 换成了文件路径。

Scanner in = new Scanner(infile);
PrintWriter out = new PrintWriter(new FileWriter(outfile));

while (--T >= 0) {
    int N = in.nextInt();

    in.skip("\n");

    while (--N >= 0) {

    }

}

C++

// 用 freopen 重定向输入输出流
freopen(infile, "r", stdin);
freopen(outfile, "w", stdout);

while(T--) {
    int N;
    cin >> N;

    // cin and getline skipping input
    // https://stackoverflow.com/questions/10553597/cin-and-getline-skipping-input
    // https://stackoverflow.com/questions/5739937/using-getlinecin-s-after-cin
    cin.ignore (numeric_limits<streamsize>::max(), '\n');

    while (N--) getline(cin, persons[N]);
}