HSSLIVE Plus One Computer Science Chapter 9: String Handling and I/O Functions Notes

This chapter focuses on text processing and input/output operations, essential elements of most practical applications. It explores C++’s capabilities for string manipulation, including character arrays and the string class, covering operations like concatenation, comparison, and substring extraction. The chapter also examines the various input/output mechanisms in C++, from console-based interactions using cin and cout to file operations for persistent data storage, including techniques for validating input and formatting output.

Chapter 9: String Handling and I/O Functions

Strings are sequences of characters used to represent text. C++ provides multiple ways to handle strings, along with various input and output operations. This chapter explores string handling and I/O functions in C++.

Character Arrays (C-style Strings)

In C++, strings can be represented as arrays of characters terminated by a null character \0.

Declaration and Initialization

cpp

// Declaration
char greeting[6];

// Initialization
char name[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char city[] = "Delhi";  // Compiler adds the null character automatically

Common Operations with C-style Strings

String Input and Output:

cpp

char name[50];
cout << "Enter your name: ";
cin >> name;  // Reads until whitespace
cout << "Hello, " << name << "!" << endl;

// Reading a line with spaces
char address[100];
cout << "Enter your address: ";
cin.ignore();  // Clear input buffer
cin.getline(address, 100);  // Reads a whole line
cout << "Your address is: " << address << endl;

String Functions (from <cstring> header):

  1. strlen(): Calculates the length of a string
#include <cstring>

char str[] = "Hello";
int length = strlen(str);  // Returns 5
  1. strcpy(): Copies one string to another
cpp

char source[] = "Hello";
char destination[10];
strcpy(destination, source);  // destination now contains "Hello"
  1. strcat(): Concatenates (joins) two strings
cpp

char first[] = "Hello, ";
char second[] = "world!";
char result[20];
strcpy(result, first);
strcat(result, second);  // result now contains "Hello, world!"
  1. strcmp(): Compares two strings
cpp

char str1[] = "apple";
char str2[] = "banana";
int comparison = strcmp(str1, str2);
// Returns negative value because "apple" comes before "banana"
  1. strchr(): Finds first occurrence of a character in a string
cpp

char text[] = "programming";
char* position = strchr(text, 'g');
// Returns pointer to first 'g' in "programming"
  1. strstr(): Finds first occurrence of a substring in a string
cpp

char text[] = "C++ programming";
char* position = strstr(text, "prog");
// Returns pointer to "programming" in "C++ programming"

The string Class

C++ provides a more powerful string class in the Standard Template Library (STL) that simplifies string operations.

Declaration and Initialization

cpp

#include <string>
using namespace std;

// Declaration and initialization
string greeting = "Hello";
string name("John");
string empty;

String Operations with the string Class

Basic Operations:

cpp

string first = "Hello";
string last = "World";

// Concatenation using + operator
string message = first + " " + last;  // "Hello World"

// String length
int length = message.length();  // or message.size()

// Accessing characters
char firstChar = message[0];  // 'H'
char lastChar = message[message.length() - 1];  // 'd'

// Modifying characters
message[0] = 'h';  // Changes to "hello World"

String Methods:

  1. append(): Adds characters to the end of a string
cpp

string text = "Hello";
text.append(" there");  // text becomes "Hello there"
  1. insert(): Inserts characters at a specified position
cpp

string sentence = "C++ fun";
sentence.insert(4, "is ");  // sentence becomes "C++ is fun"
  1. erase(): Removes characters from a string
cpp

string word = "programming";
word.erase(0, 3);  // Removes first 3 characters, word becomes "gramming"
  1. replace(): Replaces parts of a string
cpp

string text = "Hello world";
text.replace(6, 5, "everyone");  // text becomes "Hello everyone"
  1. substr(): Extracts a substring
cpp

string sentence = "C++ programming is fun";
string sub = sentence.substr(4, 11);  // sub becomes "programming"
  1. find(): Searches for a substring
cpp

string text = "programming in C++";
size_t position = text.find("in");  // position is 12
  1. compare(): Compares strings
cpp

string str1 = "apple";
string str2 = "banana";
int result = str1.compare(str2);  // Returns negative value

Input/Output Operations

Standard I/O Streams

C++ provides predefined streams for standard input, output, and error:

  • cin: Standard input stream (keyboard)
  • cout: Standard output stream (console)
  • cerr: Standard error stream (console, unbuffered)
  • clog: Standard error stream (console, buffered)

Basic Input/Output

cpp

int age;
string name;

// Output
cout << "Enter your name: ";

// Input
cin >> name;
cout << "Enter your age: ";
cin >> age;

// Combined output
cout << "Hello, " << name << "! You are " << age << " years old." << endl;

Formatting Output

cpp

#include <iostream>
#include <iomanip>  // Required for formatting manipulators
using namespace std;

int main() {
    double pi = 3.14159265359;
    
    // Setting precision
    cout << "Default: " << pi << endl;
    cout << "Fixed with 2 decimal places: " << fixed << setprecision(2) << pi << endl;
    
    // Width and alignment
    cout << setw(10) << "Name" << setw(5) << "Age" << endl;
    cout << setw(10) << "John" << setw(5) << 25 << endl;
    cout << setw(10) << "Alice" << setw(5) << 22 << endl;
    
    // Base (decimal, octal, hexadecimal)
    int number = 42;
    cout << "Decimal: " << dec << number << endl;
    cout << "Octal: " << oct << number << endl;
    cout << "Hexadecimal: " << hex << number << endl;
    
    return 0;
}

Input Manipulators

cpp

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int number;
    
    // Specify base for input
    cout << "Enter a hexadecimal number: ";
    cin >> hex >> number;
    cout << "In decimal: " << dec << number << endl;
    
    // Skip whitespace
    char character;
    cout << "Enter a character: ";
    cin >> noskipws >> character;  // Does not skip whitespace
    
    return 0;
}

Reading Entire Lines

cpp

#include <iostream>
#include <string>
using namespace std;

int main() {
    string fullName;
    
    cout << "Enter your full name: ";
    getline(cin, fullName);  // Reads entire line including spaces
    
    cout << "Hello, " << fullName << "!" << endl;
    
    return 0;
}

File Input/Output

File I/O in C++ allows programs to read from and write to files.

Opening and Closing Files

cpp

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    // Writing to a file
    ofstream outFile("example.txt");
    
    if (outFile.is_open()) {
        outFile << "Hello, File I/O!" << endl;
        outFile << "This is a sample text file." << endl;
        outFile.close();
        cout << "File written successfully." << endl;
    } else {
        cout << "Unable to open file for writing." << endl;
    }
    
    // Reading from a file
    ifstream inFile("example.txt");
    string line;
    
    if (inFile.is_open()) {
        cout << "File contents:" << endl;
        while (getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    } else {
        cout << "Unable to open file for reading." << endl;
    }
    
    return 0;
}

File Modes

Files can be opened in different modes:

cpp

// Write mode (creates new file or truncates existing file)
ofstream outFile("data.txt");

// Append mode (adds content to end of file)
ofstream appendFile("data.txt", ios::app);

// Binary mode
ofstream binaryFile("data.bin", ios::binary);

// Multiple modes
fstream file("data.txt", ios::in | ios::out | ios::app);

Common file modes:

  • ios::in: Open for reading
  • ios::out: Open for writing
  • ios::app: Append mode
  • ios::trunc: Truncate existing file
  • ios::binary: Binary mode
  • ios::ate: Position at end of file on opening

Reading and Writing Binary Data

cpp

#include <iostream>
#include <fstream>
using namespace std;

struct Student {
    int id;
    char name[50];
    float gpa;
};

int main() {
    Student s1 = {101, "Rahul Kumar", 9.2};
    
    // Writing binary data
    ofstream outFile("student.dat", ios::binary);
    if (outFile.is_open()) {
        outFile.write(reinterpret_cast<char*>(&s1), sizeof(Student));
        outFile.close();
        cout << "Student data written to file." << endl;
    }
    
    // Reading binary data
    Student s2;
    ifstream inFile("student.dat", ios::binary);
    if (inFile.is_open()) {
        inFile.read(reinterpret_cast<char*>(&s2), sizeof(Student));
        inFile.close();
        
        cout << "Student data read from file:" << endl;
        cout << "ID: " << s2.id << endl;
        cout << "Name: " << s2.name << endl;
        cout << "GPA: " << s2.gpa << endl;
    }
    
    return 0;
}

Practical Applications

Example 1: Word Counter

cpp

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    string filename;
    cout << "Enter filename: ";
    getline(cin, filename);
    
    ifstream file(filename);
    if (!file.is_open()) {
        cout << "Unable to open file: " << filename << endl;
        return 1;
    }
    
    int chars = 0, words = 0, lines = 0;
    string line;
    bool inWord = false;
    
    while (getline(file, line)) {
        lines++;
        chars += line.length();
        
        for (char c : line) {
            if (isspace(c)) {
                inWord = false;
            } else if (!inWord) {
                inWord = true;
                words++;
            }
        }
    }
    
    file.close();
    
    cout << "File statistics:" << endl;
    cout << "Characters: " << chars << endl;
    cout << "Words: " << words << endl;
    cout << "Lines: " << lines << endl;
    
    return 0;
}

Example 2: Simple Text Editor

cpp

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

void displayMenu() {
    cout << "\n--- TEXT EDITOR MENU ---" << endl;
    cout << "1. Create new file" << endl;
    cout << "2. Open and display file" << endl;
    cout << "3. Append to file" << endl;
    cout << "4. Search text in file" << endl;
    cout << "5. Exit" << endl;
    cout << "Enter your choice: ";
}

void createFile() {
    string filename, line;
    cout << "Enter filename: ";
    cin >> filename;
    cin.ignore();
    
    ofstream file(filename);
    if (!file.is_open()) {
        cout << "Unable to create file." << endl;
        return;
    }
    
    cout << "Enter text (type END on a new line to finish):" << endl;
    while (true) {
        getline(cin, line);
        if (line == "END") break;
        file << line << endl;
    }
    
    file.close();
    cout << "File created successfully." << endl;
}

void displayFile() {
    string filename;
    cout << "Enter filename: ";
    cin >> filename;
    
    ifstream file(filename);
    if (!file.is_open()) {
        cout << "Unable to open file." << endl;
        return;
    }
    
    string line;
    cout << "\n--- FILE CONTENTS ---" << endl;
    while (getline(file, line)) {
        cout << line << endl;
    }
    
    file.close();
}

void appendToFile() {
    string filename, line;
    cout << "Enter filename: ";
    cin >> filename;
    cin.ignore();
    
    ofstream file(filename, ios::app);
    if (!file.is_open()) {
        cout << "Unable to open file." << endl;
        return;
    }
    
    cout << "Enter text to append (type END on a new line to finish):" << endl;
    while (true) {
        getline(cin, line);
        if (line == "END") break;
        file << line << endl;
    }
    
    file.close();
    cout << "Text appended successfully." << endl;
}

void searchInFile() {
    string filename, searchText;
    cout << "Enter filename: ";
    cin >> filename;
    cin.ignore();
    
    cout << "Enter text to search: ";
    getline(cin, searchText);
    
    ifstream file(filename);
    if (!file.is_open()) {
        cout << "Unable to open file." << endl;
        return;
    }
    
    string line;
    int lineNum = 0;
    bool found = false;
    
    cout << "\n--- SEARCH RESULTS ---" << endl;
    while (getline(file, line)) {
        lineNum++;
        size_t pos = line.find(searchText);
        if (pos != string::npos) {
            cout << "Line " << lineNum << ": " << line << endl;
            found = true;
        }
    }
    
    if (!found) {
        cout << "Text not found in the file." << endl;
    }
    
    file.close();
}

int main() {
    int choice;
    
    do {
        displayMenu();
        cin >> choice;
        
        switch (choice) {
            case 1:
                createFile();
                break;
            case 2:
                displayFile();
                break;
            case 3:
                appendToFile();
                break;
            case 4:
                searchInFile();
                break;
            case 5:
                cout << "Exiting program. Goodbye!" << endl;
                break;
            default:
                cout << "Invalid choice. Please try again." << endl;
        }
    } while (choice != 5);
    
    return 0;
}

String handling and I/O operations are fundamental aspects of C++ programming that allow for effective text processing and interaction with users and files. Mastering these concepts enables programmers to develop applications that can process text data efficiently and communicate effectively with users through various input and output channels.

Complete Chapter-wise Hsslive Plus One Computer Science Notes

Our HSSLive Plus One Computer Science Notes cover all chapters with key focus areas to help you organize your study effectively:

Leave a Comment