c++databasefstreamvoting

How to compare new string name with existing from txt file?


I want to implement a simple function in a voting program that is searching for a name, and if this name is already existing then it will show a message that a person cannot vote. But I'm so confused with txt files. The code below does not work properly, I want to understand what I need to do. Also, how to find a full name? I think it is only searching for the first word

bool searchname(string mainvoter);

int main()
{ 
    ofstream newvoter("voter.txt", ios::app);
    string name;
     cout<<"Enter your name: ";
     getline(cin, name);
     newvoter << name << endl;;
     newvoter.close(); 
     if(searchname(name)){
        cout<<"This person already voted!"<<endl;
     }
     else
        cout<<"Okay!"<<endl;   
 }

bool searchname(string mainvoter)
{
     ifstream voter("voter.txt");
     string name;    
     while (voter >> name ){  
           if (mainvoter == name){
             return 1;
          }
         else
             return 0;
         } 
 }

Solution

  • You return false if the first name in the file does not match mainvoter. Comments in code with the suggested changes:

    bool searchname(const std::string& mainvoter) // const& instead of copying the string.
    {                                             // It's not strictly needed, but is often
                                                  // more effective.
        std::ifstream voter("voter.txt");
    
        if(voter) {                        // check that the file is in a good (and open) state
            std::string name;    
            while(std::getline(voter, name)) { // see notes
                if(mainvoter == name) {        // only return if you find a match
                    return true;               // use true instead of 1
                }
            }
        } 
        // return false here, when the whole file has been parsed (or you failed to open it)
        return false;                      // and use false instead of 0
    }
    

    Other notes: