ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP1112Input Output Construct…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP1112

    Programming Fundamentals

    Progress0 / 19 done
    Topics19
    1Introduction to Problem Solving2Von-Neumann Architecture3Introduction to Programming4Role of Compiler and Linker5Introduction to Algorithms6Basic Data Types and Variables7Input/Output Constructs8Arithmetic, Comparison and Logical Operators9Conditional Statements and Execution Flow10Repetitive Statements and Execution Flow11Lists and Memory Organization12Multi-dimensional Lists13Introduction to Modular Programming14Function Definition and Calling15Stack Rolling and Unrolling16Strings and String Operations17Pointers/References18Static and Dynamic Memory Allocation19File I/O Operations
    4 min read
    Topic 7 of 19
    Topic Study Note Illustration
    07

    Input/Output Constructs

    Input and output (I/O) are fundamental operations in programming that allow a program to interact with the user or other systems. In C++, these operations are primarily...

    Input/Output Constructs in Programming

    Input and output (I/O) are fundamental operations in programming that allow a program to interact with the user or other systems. In C++, these operations are primarily handled using streams, which are abstractions that represent sequences of characters. Here’s a detailed overview of input/output constructs, particularly in C++.

    1. Basic I/O Streams

    C++ provides two standard I/O streams for handling input and output:

    • std::cin: Used for standard input (usually from the keyboard).
    • std::cout: Used for standard output (usually to the console).

    These streams are part of the <iostream> header, which you need to include in your program.

    Example:

    #include <iostream>
    using namespace std;
    
    int main() {
        int age;
        cout << "Enter your age: "; // Output to the console
        cin >> age;                 // Input from the user
        cout << "You are " << age << " years old." << endl; // Output the age
        return 0;
    }
    

    2. Output Constructs

    Using std::cout:

    • The << operator is used to send output to std::cout.
    • You can chain multiple outputs together.

    Example:

    cout << "Hello, " << name << "! Welcome to C++ programming." << endl;
    

    Manipulators: C++ provides several manipulators to format output, such as:

    • std::endl: Inserts a newline and flushes the output buffer.
    • std::fixed: Sets floating-point output to fixed-point notation.
    • std::setprecision(n): Sets the number of decimal places for floating-point output.

    Example with Manipulators:

    #include <iostream>
    #include <iomanip> // For std::setprecision
    using namespace std;
    
    int main() {
        double pi = 3.14159;
        cout << "Value of Pi: " << fixed << setprecision(2) << pi << endl;
        return 0;
    }
    

    3. Input Constructs

    Using std::cin:

    • The >> operator is used to read input from std::cin.
    • Input can be stored in variables, which should be declared before reading.

    Example:

    int number;
    cout << "Enter a number: ";
    cin >> number; // Read user input into the variable
    

    Input Validation: It's important to validate user input to ensure it meets expected criteria.

    Example:

    int age;
    cout << "Enter your age: ";
    while (!(cin >> age) || age < 0) { // Validate input
        cin.clear(); // Clear the error flag
        cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Discard invalid input
        cout << "Invalid input. Please enter a positive integer: ";
    }
    

    4. File I/O

    In addition to standard input/output, C++ also allows you to read from and write to files using file streams. This is accomplished using std::ifstream (input file stream) and std::ofstream (output file stream) from the <fstream> header.

    Example of File Output:

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main() {
        ofstream outFile("output.txt"); // Create an output file stream
        if (outFile.is_open()) {
            outFile << "Hello, File!" << endl; // Write to the file
            outFile.close(); // Close the file
        } else {
            cout << "Unable to open file." << endl;
        }
        return 0;
    }
    

    Example of File Input:

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main() {
        ifstream inFile("input.txt"); // Create an input file stream
        if (inFile.is_open()) {
            string line;
            while (getline(inFile, line)) { // Read lines from the file
                cout << line << endl; // Output each line to the console
            }
            inFile.close(); // Close the file
        } else {
            cout << "Unable to open file." << endl;
        }
        return 0;
    }
    

    5. Error Handling in I/O

    It's important to handle errors during I/O operations, such as checking if a file opened successfully or if user input was valid.

    • Use the .is_open() method to check if a file stream is successfully opened.
    • Use .fail() or .eof() to check for input errors or the end of the file.

    Example:

    if (!inFile) {
        cerr << "Error opening file!" << endl; // Output error message
    }
    

    Conclusion

    Input and output constructs are vital for interaction in programming. In C++, using std::cin and std::cout provides a straightforward way to handle console I/O, while file streams enable reading from and writing to files. Understanding these constructs allows you to create more interactive and user-friendly applications.

    ← Previous topic 6
    Basic Data Types and Variables
    Next topic 8 →
    Arithmetic, Comparison and Logical Operators

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    4mremaining
    715words
    Beginnerlevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals