Permalink
Browse files

Update notes on I/O

  • Loading branch information...
hparra committed Mar 1, 2017
1 parent 87a06cf commit b6bd9ae4f11e27e8e845377f52ffc6f3f728b114
Showing with 29 additions and 1 deletion.
  1. +29 −1 io.md
View
30 io.md
@@ -26,9 +26,37 @@ There are various C functions to read data from a stream:
TIP: Beware of using `scanf` followed by a different function to read a string, as `scanf` will leave the newline in the stream buffer. The following call, e.g. `fgets` will encounter this newline and immediately return. You can use `getchar` to eat this newline first.
-# Python
+### Python
`raw_input` is similar to a `getline` but is only valid in Python 2.
Use `sys.stdout.write` for more control.
Remember to also use `sys.stdout.flush` to ensure buffer is written immediately.
+
+Some quickies:
+- read an integer on a line: `int(raw_input().strip())`
+- read array of integer from space-separated integers on a line: `map(lambda x: int(x), raw_input().strip().split(' '))`
+
+`print(",".join(map(str, array)))`
+
+### Java
+
+- `System.out` for STDOUT
+- `System.in` for STDIN
+
+```java
+// Read a string and integer from stdin
+Scanner scanner = new Scanner(System.in);
+String str = scanner.next();
+int num = scanner.nextInt();
+scanner.close();
+```
+
+```java
+// Read until EOF
+Scanner scanner = new Scanner(System.in);
+while (scanner.hasNext()) {
+ int a = scanner.nextInt();
+ System.out.println(a);
+}
+```

0 comments on commit b6bd9ae

Please sign in to comment.