0% found this document useful (0 votes)
11 views2 pages

Create A File and Display The Content of The File With Line Numbersin C++

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 views2 pages

Create A File and Display The Content of The File With Line Numbersin C++

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/ 2

9.

CREATE A FILE AND DISPLAY THE CONTENT OF THE FILE WITH


LINE NUMBERSIN C++

#include <iostream>
#include <fstream>

int main() {
// Create and open a text file
std::ofstream outFile("example.txt");
if (outFile) {
outFile << "Hello, World!\n";
outFile << "This is a simple file example.\n";
outFile << "Enjoy coding in C++!\n";
outFile.close(); // Close the file after writing
}

// Open the file for reading


std::ifstream inFile("example.txt");
std::string line;
int lineNumber = 1;

// Check if the file is open


if (inFile) {
while (std::getline(inFile, line)) {
std::cout << lineNumber << ": " <<line << std::endl;
std::cout<<"Totla number of lines"<<lineNumber++ << std::endl;
//Display line number and content
}
inFile.close(); // Close the file after reading
} else {
std::cerr << "Error opening file!" << std::endl;
}

return 0;
}
OUTPUT

You might also like