Writing to a file

Hello, I am trying to make a simple program, I would like it to be able to do the following,
Write a program that opens two text files (input1.txt and input2.txt) for
input .The program should write the followings in the two files. input1.txt:

This is the first line in input1.txt.
This is the second line in input1.txt.
This is the third line in input1.txt.
This is the fourth line in input1.txt.

input2.txt:

This is the first line in input2.txt.
This is the second line in input2.txt.
This is the third line in input2.txt.

What would be the best way to go about doing this?
I wrote the program below, but I don't think that it works.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <string>

int main()
{
	using namespace std;
	string input1;
	
	ofstream fout(input1.c_str());
	fout<<"This is the first line in input1.txt.\n";
	fout<<"This is the second line in input1.txt.\n";
	fout<<"This is the third line in input1.txt.\n";
	fout<<"This is the fourth line in input1.txt.\n";
	cout<<"The first line was added to input1"<<endl;
	cout<<"The second line was added to input1"<<endl;
	cout<<"The third line was added to input1"<<endl;
	cout<<"The fourth line was added to input1"<<endl;
	fout.close();
	cin.get();
	cin.get();
	return 0;
}
Rather than opening the file through the "string" input1, actually declare that you are opening a text file to open. This is how you should do it:

 
ofstream fout("input1.txt");


After that, to open the second one, simply open the ofstream object again with your other file, like so:

19
20
21
22
23
fout.close();

fout.open("input2.txt");
// output your text
fout.close();


EDIT:
Also, in a formatting perspective, you probably want to put your output to the console directly after the respective file output statement, as it makes more logical sense, as in
1
2
3
4
5
fout<<"This is the first line in input1.txt.\n";
cout<<"The first line was added to input1"<<endl;
fout<<"This is the second line in input1.txt.\n";
cout<<"The second line was added to input1"<<endl;
//etc. 
Last edited on
Thank you so much! That was the problem!
Topic archived. No new replies allowed.