Input from keybaord | Java to C++ |
This shows how to read values that the user types at the keyboard. Note that for most of these methods, nothing will be received until after the user presses <enter>. This allows the user to backspace and retype mistakes before sending the input to the program.
ImportingIn Java, the easiest way to access input from the keyboard is through the Scanner class. This is imported at Main.java[1]. Similarly in C++ we include the <iostream> file at Main.cpp[1]. Don't forget the namespace at Main.cpp[3]. Input sourceIn Java we get input from the keyboard via System.in. We connect this to a scanner as shown at Main.java[5]. In C++ this is simpler. We access keyboard input from the variable cin, which was declared inside of <iostream>. We don't need anything like Scanner in C++. Reading inputTo read in an integer in Java we used the nextInt() method shown at Main.java[9]. To do the same thing in C++ we use the >> operator as shown at Main.cpp[9]. We can read double values in a similar way as shown at Main.java[11] and Main.cpp[11]. Reading strings is special. In both languages, reading a string simply reads until the first space or the end of line is found. This will read in single words at a time. In Java we can read the first name followed by the last name as shown in Main.java[18-19]. We can do a similar thing in C++ as shown at Main.cpp[19]. |