Basic
Practice Problems based on chapter which you learn in previous Tutorials.
1. Write a Sentence in File
#include <iostream>
Copy Code
int
main
() {
std::ofstream
outputFile("example.txt");
if
(!outputFile.is_open()) {
std::cerr
<< "Error opening the file!" << std::endl;
return
1;
}
outputFile
<< "Hello, this is a sentence written to a file in C++." << std::endl;
outputFile
.close();
std::cout
<< "Sentence successfully written to the file." << std::endl;
return
0;
}
2. Read the first Line from File
#include <iostream>
Copy Code
int
main
() {
std::ifstream
inputFile("example.txt");
if
(!inputFile.is_open()) {
std::cerr
<<
"Error opening the file!"
<< std::endl;
return
1;
}
std::string
firstLine;
std::getline
(inputFile, firstLine);
inputFile
.close();
std::cout
<<
"First line from the file: "
<< firstLine << std::endl;
return
0;
}