Input/output files help.

I'm sorry this is a little long.. but please help if you can.
Here is my code.
When I am opening a txt file and transferring its content into a different selected txt file, it always have one "word" too many. Any ideas?

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <algorithm>


using namespace std;

//bool duplicate;
void filter(vector < string > & filter_vector, string word)
{
	bool copy = false;

	for(int i = 0; i < filter_vector.size(); i++)
	{

		if(word == filter_vector[i])

		{
			copy = true;
		}
	}

	if(copy == false)
	{
		filter_vector.push_back(word);

	}
}

//open file;
int main()
{
	cout << "Please enter the file name: ";
	string file;
	getline(cin, file);
	ifstream in_file;
	in_file.open(file.c_str());

	if(in_file.fail())
	{
		cout << "the file \"" << file << "\" cannot be found." << endl;

		return main() ;
	}
	else
	{

		cout << "the file \"" << file << "\" is now opened." << endl;
	}

	vector<string> word2;
	string word;

	while(in_file >> word)
	{
		filter(word2, word);
	}



	sort(word2.begin()+1, word2.end());

	ofstream out_file;

	string out;
	cout << "Enter your output file name: ";
	getline(cin, out);

	out_file.open(out.c_str());

	out_file << word2.size() << endl;

	for(int i = 1; i < word2.size(); i++)
	{
		out_file << word2[i] << endl;
	}

	system("pause");
	return 0;
}
for(int i = 1; i < word2.size(); i++)
Indexes starts from 0: for(int i = 0; i < word2.size(); i++)
Even better:
1
2
for(auto x: word2)
    out_file << x << endl;


Some notes:
1) Latest standart version can take strings instead of c-strings as arguments almost everywhere.
2) You can tell which file to open in constructor
Combining both:
1
2
3
4
cout << "Please enter the file name: ";
string file;
getline(cin, file);
ifstream in_file(file);

3)return main() ;
Do not do that. Ever. Do not call main().
Topic archived. No new replies allowed.