常用编程语言的标准输入和标准输出及其重定向
什么是标准输入和标准输出?
标准输入(stdin)和标准输出(stdout)是程序与外面世界可以进行相互的数据流。当从控制台运行一个程序,stdin就是把键盘上的输入读入到程序里面,stdout是把输出数据打印到屏幕上。
标准输入和标准输出的重定向
在Linux、Mac OS/X和Windows系统,可以用 < 和 > 重定向标准输入和标准输出。 例如:
MY_PROGRAM < input_file.txt > output_file.txt
这样,程序会把 input_file.txt 文件中的内容当做标准输入,而标准输入的内容会写入到 output_file.txt 里面去。
MY_PROGRAM 是指运行程序的命令,举例:
./my_binary
java my_java_binary_name
python my_python_code.py
标准输入和标准输出的代码
下面总结一些常用编程语言的标准输入和标准输出的代码(只列举了一种写法)
//C++
#include <iostream>
using namespace std;
void main() {
int t, n, m;
cin >> t;
for (int i = 1; i <= t; ++i) {
cin >> n >> m;
cout << "Case #" << i << ": " << (n + m) << " " << (n * m) << endl;
}
}
//Java
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int t = in.nextInt(); // Scanner has functions to read ints, longs, strings, chars, etc.
for (int i = 1; i <= t; ++i) {
int n = in.nextInt();
int m = in.nextInt();
System.out.println("Case #" + i + ": " + (n + m) + " " + (n * m));
}
}
}
#Python 2
t = int(raw_input())
for i in xrange(1, t + 1):
n, m = [int(s) for s in raw_input().split(" ")]
print "Case #{}: {} {}".format(i, n + m, n * m)
#Python 3
t = int(input())
for i in range(1, t + 1):
n, m = [int(s) for s in input().split(" ")]
print("Case #{}: {} {}".format(i, n + m, n * m))
(参考自Google Code Jam Quick-Start)