Write to file with check for duplicates gone wrong

The idea was to open a file with a list of names, ask the user for a name, check if it alreasy exists in the file, and if it doesn't, add it to the end of the file in a new line.
The first time it finds a duplicate name everything works OK and it urges the user to give another name. The problem is that if the name I try next is also a duplicate it adds it to the file. For some reason the 'nametaken' doesn't change from 'no' to 'yes' when it finds the duplicate.

I know the program is a mess, so if you have any suggestion about changes that would make my life easier, feel free to post.
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
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    string filename,line,addname, nametaken;
    filename = "List.txt";

    ifstream myfile (filename.c_str());
            if ( myfile.is_open())
            {
                do {
                    nametaken = "no";
                    
                    cout << "\nPlease enter 'x' to exit or enter a name: ";
                    cin >> addname;
                    cin.ignore();
                    
                    if (addname == "x") break;
                    
                    while (getline(myfile,line))    {
                        if (addname == line)     {
                        cout << addname << " is taken.\n";
                        nametaken = "yes";
                        break;
                        }
                    }
                }while (nametaken == "yes");
        
                myfile.close();
        
                if (nametaken == "no" &&  addname != "x")     {
                    ofstream myfile;
                    myfile.open (filename.c_str(), ios::out | ios::app);
                    if (myfile.is_open())   {
                        myfile << "\n" << addname;
                        myfile.close();
                    }
                }
        
            }
return 0;
}
Last edited on
You need to start reading myfile from the beginning again each time through the loop. You can do that like this:
1
2
myfile.clear(); // clear error flags (like eof)
myfile.seekg(0); // move read pointer to beginning of file 
Last edited on
I knew it would be something silly like this. Thanks a lot.
Topic archived. No new replies allowed.