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.
#include <cstring>
char str[] = "Hello";
int length = strlen(str); // Returns 5
strcpy()
: Copies one string to another
char source[] = "Hello";
char destination[10];
strcpy(destination, source); // destination now contains "Hello"
strcat()
: Concatenates (joins) two strings
char first[] = "Hello, ";
char second[] = "world!";
char result[20];
strcpy(result, first);
strcat(result, second); // result now contains "Hello, world!"
strcmp()
: Compares two strings
char str1[] = "apple";
char str2[] = "banana";
int comparison = strcmp(str1, str2);
// Returns negative value because "apple" comes before "banana"
strchr()
: Finds first occurrence of a character in a string
char text[] = "programming";
char* position = strchr(text, 'g');
// Returns pointer to first 'g' in "programming"
strstr()
: Finds first occurrence of a substring in a string
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
#include <string>
using namespace std;
// Declaration and initialization
string greeting = "Hello";
string name("John");
string empty;
String Operations with the string Class
Basic Operations:
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:
append()
: Adds characters to the end of a string
string text = "Hello";
text.append(" there"); // text becomes "Hello there"
insert()
: Inserts characters at a specified position
string sentence = "C++ fun";
sentence.insert(4, "is "); // sentence becomes "C++ is fun"
erase()
: Removes characters from a string
string word = "programming";
word.erase(0, 3); // Removes first 3 characters, word becomes "gramming"
replace()
: Replaces parts of a string
string text = "Hello world";
text.replace(6, 5, "everyone"); // text becomes "Hello everyone"
substr()
: Extracts a substring
string sentence = "C++ programming is fun";
string sub = sentence.substr(4, 11); // sub becomes "programming"
find()
: Searches for a substring
string text = "programming in C++";
size_t position = text.find("in"); // position is 12
compare()
: Compares strings
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
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
#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
#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
#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
#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:
// 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 readingios::out
: Open for writingios::app
: Append modeios::trunc
: Truncate existing fileios::binary
: Binary modeios::ate
: Position at end of file on opening
Reading and Writing Binary Data
#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
#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
#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:
- Chapter 1 The Discipline of Computing
- Chapter 2 Data Representation and Boolean Algebra
- Chapter 3 Components of the Computer System
- Chapter 4 Principles of Programming and Problem Solving
- Chapter 5 Introduction to C++ Programming
- Chapter 6 Data Types and Operators
- Chapter 7 Control Statements
- Chapter 8 Arrays
- Chapter 9 String Handling and I/O Functions
- Chapter 10 Functions
- Chapter 11 Computer Networks
- Chapter 12 Internet and Mobile Computing