Python Input and File Handling (Compared with C++)
1. User Input
-------------
Python:
-----------
name = input("Enter your name: ")
print("Hello", name)
age = int(input("Enter your age: "))
print("Next year, you will be", age + 1)
C++:
-----------
#include <iostream>
using namespace std;
int main() {
string name;
int age;
cout << "Enter your name: ";
cin >> name;
cout << "Enter your age: ";
cin >> age;
cout << "Hello " << name << ", next year you will be " << age + 1 << endl;
return 0;
}
Key Differences:
- Python uses input() for all data types and then casts if needed.
- C++ uses cin for standard input, with type-specific variables.
2. File Handling
-----------------
Opening a File:
Python:
file = open("example.txt", "r")
C++:
#include <fstream>
ifstream file("example.txt");
Reading from a File:
Python:
with open("example.txt", "r") as f:
contents = f.read()
print(contents)
C++:
#include <fstream>
#include <string>
using namespace std;
ifstream file("example.txt");
string line;
while (getline(file, line)) {
cout << line << endl;
Writing to a File:
Python:
with open("output.txt", "w") as f:
f.write("Hello, file!")
C++:
#include <fstream>
ofstream file("output.txt");
file << "Hello, file!";
Appending to a File:
Python:
with open("output.txt", "a") as f:
f.write("\nAppended line")
C++:
ofstream file("output.txt", ios::app);
file << "\nAppended line";
Closing a File:
Python uses `with` which handles closing automatically.
Manual closing: file.close()
C++ must call file.close() or rely on object destruction.
Conclusion:
- Python simplifies input and file operations with fewer lines and higher-level functions.
- C++ requires more verbose syntax but offers fine-grained control and performance.
This document highlights both similarities and differences for learners transitioning between the two langua