C++ Tutorial

Class and Object

Reference

Inheritance and Derivation

Polymorphism and Virtual Functions

Operator Overloading

Template

Exception

Object Oriented Advanced

Input/Output Stream

File Operations

Input And Output Streams in C++

In C++, input and output streams are used for handling data flow. The standard library provides a set of classes for stream-based input and output operations. These classes can be found in the iostream header.

In this tutorial, we'll cover the basics of using input and output streams in C++.

  • Include the required headers:

To use input and output streams, include the iostream header.

#include <iostream>
  • Output Streams:

ostream is a class that represents output streams. std::cout is an instance of the ostream class, which is used for writing data to the standard output (typically the console).

To write data to an output stream, use the insertion operator <<.

Example:

int main() {
    std::cout << "Hello, world!" << std::endl;
    return 0;
}
  • Input Streams:

istream is a class that represents input streams. std::cin is an instance of the istream class, which is used for reading data from the standard input (typically the keyboard).

To read data from an input stream, use the extraction operator >>.

Example:

int main() {
    int age;
    std::cout << "Enter your age: ";
    std::cin >> age;
    std::cout << "You are " << age << " years old." << std::endl;
    return 0;
}
  • File Streams:

File streams are used to read and write data to files. To use file streams, include the fstream header.

The ofstream class is used for writing data to files, and the ifstream class is used for reading data from files.

Example:

#include <iostream>
#include <fstream>

int main() {
    // Writing to a file
    std::ofstream outfile("output.txt");
    outfile << "Hello, file!" << std::endl;
    outfile.close();

    // Reading from a file
    std::ifstream infile("output.txt");
    std::string line;
    while (std::getline(infile, line)) {
        std::cout << line << std::endl;
    }
    infile.close();

    return 0;
}
  • Manipulators:

Manipulators are used to format the input and output. Some common manipulators include std::setw, std::setprecision, and std::fixed.

Example:

#include <iostream>
#include <iomanip>

int main() {
    double pi = 3.141592653589793238;
    std::cout << std::setprecision(5) << pi << std::endl;
    std::cout << std::setprecision(10) << pi << std::endl;
    std::cout << std::fixed << std::setprecision(3) << pi << std::endl;
    return 0;
}

Output:

3.1416
3.141592654
3.142
  • Error Handling:

You can check for errors during input and output operations using the stream's member functions, such as eof(), fail(), bad(), and good().

Example:

#include <iostream>
#include <fstream>

int main() {
    std::ifstream infile("nonexistent.txt");
    if (infile.fail()) {
        std::cerr << "Error opening file." << std::endl;
        return 1;
    }

    std::string line;
    while (std::getline(infile, line)) {
        std::cout << line << std::endl;
    }
    infile.close();

    return 0;
}
  1. How to work with streams in C++:

    • Description: Introduces the concept of streams in C++ and their role in handling input and output operations.
    • Example Code:
      #include <iostream>
      
      int main() {
          // Output to console
          std::cout << "Hello, C++ streams!" << std::endl;
      
          // Input from console
          int num;
          std::cout << "Enter a number: ";
          std::cin >> num;
      
          std::cout << "You entered: " << num << std::endl;
      
          return 0;
      }
      
  2. Using stream classes in C++:

    • Description: Discusses the fundamental stream classes in C++, including cin, cout, cerr, and clog.
    • Example Code:
      #include <iostream>
      
      int main() {
          int x = 42;
          std::cout << "Using cout: " << x << std::endl;
          std::cerr << "Using cerr: " << x << std::endl;
          std::clog << "Using clog: " << x << std::endl;
      
          return 0;
      }
      
  3. C++ input and output stream operators:

    • Description: Explores the << (insertion) and >> (extraction) operators for input and output streams in C++.
    • Example Code:
      #include <iostream>
      
      int main() {
          int x = 42;
          std::cout << "Using cout: " << x << std::endl;
      
          int y;
          std::cout << "Enter a number: ";
          std::cin >> y;
          std::cout << "You entered: " << y << std::endl;
      
          return 0;
      }
      
  4. Stream manipulators in C++:

    • Description: Introduces stream manipulators for controlling formatting and behavior of C++ streams.
    • Example Code:
      #include <iostream>
      #include <iomanip>
      
      int main() {
          double pi = 3.14159;
      
          // Setting precision and width
          std::cout << std::fixed << std::setprecision(2) << "Value of pi: " << pi << std::endl;
      
          return 0;
      }
      
  5. Working with standard input stream (cin) in C++:

    • Description: Demonstrates how to work with the standard input stream cin for user input in C++.
    • Example Code:
      #include <iostream>
      
      int main() {
          int age;
          std::cout << "Enter your age: ";
          std::cin >> age;
          std::cout << "You are " << age << " years old." << std::endl;
      
          return 0;
      }
      
  6. Standard output stream (cout) in C++:

    • Description: Illustrates the use of the standard output stream cout for displaying output in C++.
    • Example Code:
      #include <iostream>
      
      int main() {
          std::cout << "Hello, C++ streams!" << std::endl;
          return 0;
      }
      
  7. File input and output streams in C++:

    • Description: Demonstrates how to perform file input and output operations using file streams in C++.
    • Example Code:
      #include <iostream>
      #include <fstream>
      
      int main() {
          // Writing to a file
          std::ofstream outputFile("output.txt");
          outputFile << "Data written to the file." << std::endl;
          outputFile.close();
      
          // Reading from a file
          std::ifstream inputFile("input.txt");
          if (inputFile.is_open()) {
              std::string line;
              while (std::getline(inputFile, line)) {
                  std::cout << line << std::endl;
              }
              inputFile.close();
          } else {
              std::cerr << "Error opening file." << std::endl;
          }
      
          return 0;
      }
      
  8. Binary file streams in C++:

    • Description: Introduces binary file streams for handling binary data in C++ file I/O.
    • Example Code:
      #include <iostream>
      #include <fstream>
      
      int main() {
          // Writing binary data to a file
          std::ofstream binaryOutputFile("binary_data.dat", std::ios::binary);
          int dataToWrite = 42;
          binaryOutputFile.write(reinterpret_cast<const char*>(&dataToWrite), sizeof(dataToWrite));
          binaryOutputFile.close();
      
          // Reading binary data from a file
          std::ifstream binaryInputFile("binary_data.dat", std::ios::binary);
          int readData;
          binaryInputFile.read(reinterpret_cast<char*>(&readData), sizeof(readData));
          std::cout << "Read binary data: " << readData << std::endl;
          binaryInputFile.close();
      
          return 0;
      }
      
  9. String streams in C++:

    • Description: Introduces stringstream for string manipulation in C++.
    • Example Code:
      #include <iostream>
      #include <sstream>
      
      int main() {
          int x = 42;
          std::stringstream ss;
          ss << "The value of x is: " << x;
          std::string result = ss.str();
          std::cout << result << std::endl;
      
          return 0;
      }
      
  10. Stream states and error handling in C++:

    • Description: Explores stream states and error handling mechanisms in C++ streams.
    • Example Code:
      #include <iostream>
      
      int main() {
          int num;
          std::cout << "Enter a number: ";
          if (std::cin >> num) {
              std::cout << "You entered: " << num << std::endl;
          } else {
              std::cerr << "Invalid input. Please enter a number." << std::endl;
          }
      
          return 0;
      }
      
  11. Using stringstream for string manipulation in C++:

    • Description: Illustrates the use of stringstream for manipulating strings in C++.
    • Example Code:
      #include <iostream>
      #include <sstream>
      
      int main() {
          std::stringstream ss;
          ss << "Concatenating " << "strings " << "using stringstream";
          std::string result = ss.str();
          std::cout << result << std::endl;
      
          return 0;
      }
      
  12. Input and output stream flags in C++:

    • Description: Discusses various flags and manipulators to control the behavior of C++ streams.
    • Example Code:
      #include <iostream>
      #include <iomanip>
      
      int main() {
          double pi = 3.14159;
      
          // Setting precision and width
          std::cout << std::fixed << std::setprecision(2) << "Value of pi: " << pi << std::endl;
      
          // Resetting flags
          std::cout.unsetf(std::ios::fixed);
      
          return 0;
      }
      
  13. Customizing stream formatting in C++:

    • Description: Demonstrates how to customize stream formatting using manipulators in C++.
    • Example Code:
      #include <iostream>
      #include <iomanip>
      
      int main() {
          double value = 123.456789;
      
          // Customizing formatting
          std::cout << std::setfill('*') << std::setw(15) << value << std::endl;
      
          return 0;
      }