0% found this document useful (0 votes)
11 views

CP Week 04 CPP Files

Uploaded by

kamran2021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

CP Week 04 CPP Files

Uploaded by

kamran2021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

CS 15X – Computer Programming

CPP Strings and Files

1
Topics covered

 Introduction to C++ Strings


 Introduction to C++ Files Handling

2
C++ Strings
• String is a collection of characters. There are two
types of strings commonly used in C++
programming language:
• Strings that are objects of string class (The
Standard C++ Library string class)
• C-strings (C-style Strings)
• C-strings are arrays of type char terminated with
null character, that is, \0 (ASCII value of null
character is 0).
char str[] = "C++";
char str[4] = "C++";
char str[] = {'C','+','+','\0'};
char str[4] = {'C','+','+','\0'};
Computer Programming 3
Example1.cpp
// C++ program to read and display an entire line entered by
// user.

#include <iostream>
using namespace std;
int main()
{
char str[100];
cout << "Enter a string: ";
cin.get(str, 100);

cout << "You entered: " << str << endl;


return 0;
}

OUTPUT:

Enter a string: Programming is fun.


You entered: Programming is fun.
Computer Programming 4
C++ String Object
• In C++, you can also create a string object for
holding strings.
• Unlike using char arrays, string objects has no
fixed length, and can be extended as per your
requirement.
• Instead of using cin>> or cin.get() function, you
can get the entered line of text using getline().
• getline() function takes the input stream as the first
parameter which is cin and str as the location of the
line to be stored.

Computer Programming 5
Example2.cpp
// C++ program to read and display an entire line entered by
// user using string object.
#include <iostream>
using namespace std;
int main()
{
// Declaring a string object
string str;
cout << "Enter a string: ";
getline(cin, str);

cout << "You entered: " << str << endl;


return 0;
}

OUTPUT:

Enter a string: Programming is fun.


You entered: Programming is fun.
Computer Programming 6
Example3.cpp
// Passing String to a Function
// Strings are passed to a function in a similar way arrays are
// passed to a function.
#include <iostream>
using namespace std;
void display(char *);
void display(string);
int main()
{
string str1;
char str[100];

cout << "Enter a string: ";


getline(cin, str1);

cout << "Enter another string: ";


cin.get(str, 100, '\n');
display(str1);
display(str);
return 0;
}
Computer Programming 7
Example3.cpp
void display(char s[])
{
cout << "Entered char array is: " << s << endl;
}

void display(string s)
{
cout << "Entered string is: " << s << endl;
}

/* We have used two functions with the same name display(). The
first function takes char array as a parameter, while the second
takes string as a parameter. This process is known as function
overloading. */

OUTPUT:

Enter a string: Programming is fun.


Enter another string: Really?
Entered string is: Programming is fun.
Entered char array is: Really?
Computer Programming 8
File Handling In C++
• Files are used to store data in a storage device
permanently.
• File handling provides a mechanism to store the
output of a program in a file and to perform
various operations on it.
• A stream is an abstraction that represents a device
on which operations of input and output are
performed.
• A stream can be represented as a source or
destination of characters of indefinite length
depending on its usage.
Computer Programming 9
File Handling In C++
• In C++, files are mainly dealt by using three
classes fstream, ifstream, ofstream.
• ofstream: This Stream class signifies the output file
stream and is applied to create files for writing
information to files
• ifstream: This Stream class signifies the input file
stream and is applied for reading information from
files
• fstream: This Stream class can be used for both
read and write from/to files.

Computer Programming 10
File Handling In C++
• C++ provides us with the following operations in
File Handling:
• Creating a file: open()
– void open(const char* file_name, ios::openmode mode);
• Reading data: read()
• Writing new data: write()
• Closing a file: close()
• Default Open Modes :
• ifstream ios::in
• ofstream ios::out
• fstream ios::in | ios::out
Computer Programming 11
File Handling In C++

Modes Description
in Opens the file to read (default for ifstream)
out Opens the file to write (default for ofstream)
binary Opens the file in binary mode
app Opens the file and appends all the outputs at the end
Opens the file and moves the control to the end of the
ate
file
trunc Removes the data in the existing file
nocreate Opens the file only if it already exists
noreplace Opens the file only if it does not already exist

Computer Programming 12
Example4.cpp
// Example of opening/creating a file using the open() function
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file.txt",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file.close(); // Step 4: Closing file
}
return 0;
}

Computer Programming 13
Example5.cpp
// Writing to a File
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file.txt",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
//Writing to file
new_file<<"Learning File handling“<<endl;
new_file.close();
}
return 0;
}
Computer Programming 14
Example5.cpp
// Writing/Appending to an existing File
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file.txt",ios::out | ios::app);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
//Writing to file
new_file<<“Programming is Fun“<<endl;
new_file.close();
}
return 0;
}
Computer Programming 15
// Reading from a File Example6.cpp
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file.txt",ios::in);
if(!new_file) {
cout<<"No such file";
}
else {
char ch;
while (!new_file.eof())
{
new_file >>ch;
cout << ch;
}
}
new_file.close();
return 0;
}
Computer Programming 16
Example7.cpp
// Reading from a File by using getline function
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
string line;
// Creation of ifstream class object to read the file
ifstream fin;
// by default open mode = ios::in mode
fin.open("new_file.txt",ios::in);
// Execute a loop until EOF (End of File)
while (fin) {
// Read a Line from File
getline(fin, line);
// Print line in Console
cout << line << endl;
}
// Close the file
fin.close();
return 0;
Computer
} Programming 17
Example8.cpp
/* File Handling with C++ using fstream class object */
/* To write the Content in File and read the content of file */
/* by default openmode = ios::in|ios::out mode overwrites the
content of file, To append the content, open in ios:app
fio.open("sample.txt", ios::in|ios::out|ios::app)
ios::trunc mode delete all content before open */
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fio;
string line;
fio.open("sample.txt", ios::trunc | ios::out | ios::in);
// Execute a loop If file successfully Opened
while (fio) {
// Read a Line from standard input
getline(cin, line);
// Press -1 to exit
if (line == "-1")
break;
// Write line in file
fio << line << endl;
Computer
} Programming 18
Example8.cpp
// Execute a loop untill EOF (End of File)
// point read pointer at beginning of file
fio.seekg(0, ios::beg);

while (fio) {

// Read a Line from File


getline(fio, line);

// Print line in Console


cout << line << endl;
}

// Close the file


fio.close();

return 0;
}

Computer Programming 19
Assignment-2
• Please go to the following tutorial:
• https://www.geeksforgeeks.org/csv-file-management-using-
c/
• And write a C++ program by combining all the functions given
in the tutorial and call it in the main function to:
• Create a CSV file containing 20 students data by using create()
function, The subjects name should be the ones you have taken
in the last semester, e.g. QCR etc.
• Read it using read_record() function
• Change/Update any students marks by using update_record()
function
• Delete record of Student number 15 by using delete_record()
function
• Submission Deadline: 1st May 2022
Computer Programming 20
References and Further Reading
• Strings and File Handling chapters of Book - Object-oriented programming in C++
By Robert Lafore, 4th Edition
• https://www.programiz.com/cpp-programming/strings
• https://www.edureka.co/blog/file-handling-in-cpp/
• https://www.geeksforgeeks.org/file-handling-c-classes/
• https://stackoverflow.com/questions/34507989/update-and-delete-data-from-file-in-c

Computer Programming 21

You might also like