I just learned on how to read and write file, and I did some practices on it. However, I'm quite confused about it. Like this example is very simple, however, I still got an error. Can someone point out my mistakes? Thank you in advance!
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
//writing a text file
ofstream myFile("hello.txt");
if (myFile.is_open())
{
myFile << "Hello, World! \n";
myFile.close();
}
else
cout << "Error : Unable to open the file. Please try again. \n";
//reading a text file
string hello;
ifstream myFile("hello.txt");
if (myFile.is_open());
{
while (getline(myFile, hello)) // getline error
{
cout << hello << '\n';
}
myFile.close();
}
else // this expected a statement? how should I fix this?
cout << "Error : Unable to open the file. Please try again. \n";
return 0;
}
The name myFile is defined earlier on line 11: ofstream myFile("hello.txt");
We can't use the same name (within the same scope) to define another object.
The error is on line 22: ofstream myFile("hello.txt");
This would be a more stylized C++ way of writing the same code.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
const std::string file_name = "hello.txt" ;
// writing a text file
if( std::ofstream out_file{file_name} ) // if the file was opened for output
{
out_file << "Hello, World! \n"; // write the greeting
// the file is automagically closed at the end of the scope (when out_file goes out of scope)
}
else std::cout << "Error : Unable to open the file " << file_name << " for output\n";
// reading a text file
if( std::ifstream in_file{file_name} ) // if the file was opened for input
{
std::string line ;
while( std::getline( in_file, line ) ) // for each line read from the file
{
std::cout << line << '\n'; // print the line that was read
}
// the file is automagically closed at the end of the scope (when in_file goes out of scope)
}
else std::cout << "Error : Unable to open the file " << file_name << " for input\n";
// there is an implicit return 0 at the end of main
}