Read and write file C++

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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  #include <iostream>
#include <fstream>
#include <string>

using namespace 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;
}
> I still got an error.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#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
}

Last edited on
Oh I see, thank you very much for helping me.
Topic archived. No new replies allowed.