Reading Input
Learn to read data from the user. Create interactive programs that respond to user input.
Learning Objectives:
- •Read integers and strings from standard input
- •Process user input in different programming languages
- •Handle multiple values on the same line
- •Convert input strings to numbers
Reading Input
Why Read Input?
So far, your programs have displayed hardcoded messages. But real programs are interactive — they ask for information from the user, process it, and respond.
Reading input is the bridge between static programs and dynamic ones.
Reading a Single Integer
The most common task is reading a whole number from the user.
Python
pythonnumber = int(input("Enter a number: ")) print(f"You entered: {number}")
Breaking it down:
input()reads a line from the user as a stringint()converts the string to an integer- The result is stored in
number
C
c#include <stdio.h> int main() { int number; printf("Enter a number: "); scanf("%d", &number); // %d means integer printf("You entered: %d\n", number); return 0; }
Key points:
scanf()reads formatted input%dspecifies we're reading an integer&numbergives the address where the value should be stored
Java
javaimport java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int number = sc.nextInt(); System.out.println("You entered: " + number); } }
C++
cpp#include <iostream> using namespace std; int main() { int number; cout << "Enter a number: "; cin >> number; cout << "You entered: " << number << endl; return 0; }
JavaScript
In Node.js, reading synchronous input is tricky. Here's one approach:
javascriptconst readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Enter a number: ', (answer) => { let number = parseInt(answer); console.log(`You entered: ${number}`); rl.close(); });
Reading a String
Often you want to read text, not just numbers.
Python
pythonname = input("Enter your name: ") print(f"Hello, {name}!")
That's it! input() returns a string by default.
C
c#include <stdio.h> int main() { char name[50]; printf("Enter your name: "); scanf("%s", name); // %s means string printf("Hello, %s!\n", name); return 0; }
Note: scanf("%s", ...) reads until whitespace. For full lines including spaces, use fgets().
Java
javaimport java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter your name: "); String name = sc.nextLine(); System.out.println("Hello, " + name + "!"); } }
Reading Multiple Values
Often you need multiple inputs.
On the Same Line
Python:
pythona, b = map(int, input("Enter two numbers: ").split()) print(f"a = {a}, b = {b}")
How it works:
input()reads "5 10" as a string.split()breaks it into ["5", "10"]map(int, ...)converts each to an integera, b =unpacks them into two variables
Java:
javaimport java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter two numbers: "); int a = sc.nextInt(); int b = sc.nextInt(); System.out.println("a = " + a + ", b = " + b); } }
Multiple Lines
Python:
pythonage = int(input("Enter your age: ")) name = input("Enter your name: ") print(f"{name} is {age} years old")
Each input() call reads a new line.
Type Conversion in Practice
When you read input, it's always a string. You must convert it:
Python
python# String to integer age_str = input("Age: ") age = int(age_str) # String to float price_str = input("Price: ") price = float(price_str)
C
c#include <stdio.h> #include <stdlib.h> int main() { char buffer[20]; // String to integer scanf("%s", buffer); int age = atoi(buffer); // ASCII to integer // String to float scanf("%s", buffer); float price = atof(buffer); // ASCII to float return 0; }
Java
javaString age_str = "25"; int age = Integer.parseInt(age_str); String price_str = "19.99"; double price = Double.parseDouble(price_str);
Real-World Example: Temperature Converter
Problem: Read a temperature in Celsius and convert to Fahrenheit.
Formula: F = (C × 9/5) + 32
Python:
pythoncelsius = float(input("Enter temperature in Celsius: ")) fahrenheit = (celsius * 9/5) + 32 print(f"{celsius}°C = {fahrenheit:.1f}°F")
Java:
javaimport java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter temperature in Celsius: "); double celsius = sc.nextDouble(); double fahrenheit = (celsius * 9/5) + 32; System.out.printf("%.1f°C = %.1f°F\n", celsius, fahrenheit); } }
C:
c#include <stdio.h> int main() { double celsius; printf("Enter temperature in Celsius: "); scanf("%lf", &celsius); double fahrenheit = (celsius * 9/5) + 32; printf("%.1f°C = %.1f°F\n", celsius, fahrenheit); return 0; }
Key Takeaways
- Input is always a string when received from the user
- Use language-specific functions:
input()(Python),scanf()(C),Scanner(Java),cin(C++) - Convert the string to the type you need:
int(),float(),Integer.parseInt(), etc. - Multiple values can be read from one line or multiple lines
- Format codes like
%d,%s,%fspecify what type you're reading
Summary
You can now read interactive input from users, making your programs respond dynamically. Combined with variables and arithmetic, you can build useful programs that solve real problems.
In the next chapter, you'll learn about conditions — the power to make decisions and execute different code based on user input.
Progress: 4/8 chapters complete in Level 1
Exercises
Exercise 1: Read a Number
Read a number from standard input and use it in the requested calculation.
Exercise 2: Read a String
Read a line of text and display the requested result.
Exercise 3: Read Multiple Values
Read several values from standard input and process them.
Exercise 4: Compute with Input
Read the provided values and calculate the requested result.
Exercise 5: Formatted Output
Format the output exactly as required by the exercise.
Exercise 6: Simple Calculator
Read two numbers and perform the requested calculator operation.