Search code examples
c++ifstreamgetline

c++ add word to file if its not there


I am making an application to add data but I am trying to add a data check that checks if the specific data being added already exists then it wont add to the file. Here is what I have but so far its not working, no errors but it just adds the data that already exists:

void checklog(const std::string& input){
    ifstream iFile("C:\\Users\\Seann\\Documents\\storedData\\data.txt");
    string line;
    while(getline(iFile, line)){
        if(input!=line){
        iFile.close();
        updateLog(input);}
    }
}

Thanks in advance to any serious answers.


Solution

  • Your if ... else attempt still makes its decision at the first line it reads, and not loop until you found the word. Try this:

    void checklog(const std::string& input){
        ifstream iFile("data.txt");
        string line;
        bool found = false; 
        while (!found && getline(iFile, line)){
            if (input == line)
                found = true;
        }
        iFile.close();
        if (found)
            updateLog(input);
    }