Unit 4
Unit 4
char data;
• Eg:
• char line[100];
• cin.getline(line, 11); // The input will be terminated after
reading 10 characters.
• cout.write(line, 11); // first arg represents name of string
and 2nd arg indicates number of characters to display
#include <iostream>
using namespace std;
int main() {
const int maxSize = 50;
char input[maxSize];
return 0;
}
The write() function displays the entire line in one go and its syntax is similar to the getline()
function only that here cout object is used to invoke it.
• cin.read(char array, max size):
• cin.read() is used to read a specified number of
characters from the input stream (cin) and stores them
in a character array.
• It reads the specified number of characters, even if they
include spaces or newline characters.
• The read() function is a member function of the input
stream classes (like istream).
• It reads a specified number of characters (n) from the
input stream and stores them in the character array s.
• It reads the specified number of characters regardless
of encountering whitespace or newline characters.
#include <iostream>
using namespace std;
int main() {
const int maxSize = 5;
char input[maxSize];
return 0;
}
OPENING AND CLOSING FILES
ios::app
1 Append mode. All output to that file to be
appended to the end.
ios::in
2
Open a file for reading.
ios::out
3
Open a file for writing.
Write a C++ program to create a text file, check file
created or not, if created write some text into the file and
then read the text from the file.
#include <iostream> cin.getline(text, sizeof(text));
#include <fstream>
using namespace std; // Writing to the file
file << text << endl;
int main() {
char text[200]; // Move the file pointer to the beginning for
fstream file; reading
file.seekg(0, ios::beg);
// Open the file in ios::out mode to create it if
it doesn't exist // Reading from the file using getline
// Open it in ios::in mode to read from it file.getline(text, sizeof(text));
file.open("example.txt", ios::out | ios::in);
// Display the text read from the file
if (!file) { cout << "Text read from the file: " << text
cout << "Error in creating/opening the << endl;
file!!!" << endl;
return 0; // Closing the file
} file.close();