Reading and Writing to a .txt file

So, I have been learning C++ for about a week or so in a camp. I started learning File I/O. The website the camp uses to teach us gave me a file (posted below) and told me to in simple terms make a copy of the file by reading the original and writing it to another .txt file. I used to sources below to get as far as I did but I do not know where to go from here. The sources below used examples that I did not understand due to explanations that didn't make sense to me. Below, the code so far creates the file sample_scores2.txt but doesn't write to it nor print the contents to the console.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>
#include <string>

int main() {
	std::ifstream infile;
	std::ofstream outfile;
	
	infile.open("sample_scores.txt", std::ios::in);
	outfile.open("sample_scores2.txt");
	std::string s;
	getline(infile, s, (char)infile.eof());
	outfile << s;
	return 0;
}
}


sample_scores.txt:
Marcos Baghdatis d. Radek Stepanek 6-4 6-3 3-6 0-6 7-5
David Nalbandian d. Danai Udomchoke 6-2 6-2 1-6 6-7 6-1
Marcos Baghdatis d. Ivan Ljubicic 6-4 6-2 4-6 3-6 6-3
Marcos Baghdatis d. David Nalbandian 3-6 5-7 6-3 6-4 6-4


SOURCES:
http://www.tutorialspoint.com/cplusplus/cpp_files_streams.htm
http://www.cplusplus.com/doc/tutorial/files/
Last edited on
> The code so far creates the file sample_scores2.txt but doesn't write to it

Because simply your program doesn't write at all. You need to add one more line :
1
2
3
getline(infile, in);
cout << in << endl;
outfile << in << endl; 
To better diagnose your problem, add more information. The more information the better.

1
2
3
4
if (infile.is_open() == false)
     cout << "Error : cannot open the file" << endl;
else
while (infile.good())
Does that help you? :)
Topic archived. No new replies allowed.