Prerequisite: Read section K.5 of Appendix K of Carrano & Henry (6th edition).
Brief summary example:
Java | C++ |
System.in , System.out , and System.err are always
available;Scanner must be "imported" if you want to use it. |
std::cin , std::cout , and std::cerr are only
available if you "include" iostream as shown. |
import java.util.Scanner; public class BasicKeyboardIO { public static void main(String[ ] args) { System.out.print("Enter two integers: "); Scanner scn = new Scanner(System.in); int i1 = scn.nextInt(); int i2 = scn.nextInt(); int sum = i1 + i2; System.out.println("The sum of " + i1 + " and " + i2 + " is " + sum); } } |
#include <iostream> int main( ) { std::cout << "Enter two integers: "; int i1, i2; std::cin >> i1 >> i2; int sum = i1 + i2; std::cout << "The sum of " << i1 << " and " << i2 << " is " << sum << '\n'; return 0; } |
The output generated by both programs is:
Enter two integers: 10 12 The sum of 10 and 12 is 22 |
There are several other general I/O strategies, methods, and operations that you will need to master. We will discuss several of these later in the section File I/O. For now it suffices to understand that the C++ input operator (>>) and output operator (<<) are type-sensitive. That is, you use the same operators regardless of whether you are reading or writing integers, floating point numbers, strings, etc.; the runtime system will parse (on input) and format (on output) according to what the types of the variables are.
What is the significance of the "std::" prefix on the identifiers "cin" and "cout"? We will get an answer to that question at the end of the next section, Identifiers at global scope.
Finally, note again Java's "import" versus C++'s "#include". We will discuss "#include" in the context of Separate compilation later.