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;
}
}
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:
You put the voter's name in the file before you check if the name exists in the file. You need to check if the name exists first and only if it does not exist in the file should you add it to the file.
You used getline
to read the name of the voter. getline
allows for whitespace characters while the formatted input, voter >> name
, that you used to read from the file does not (per default). So, if you enter "Nastya Osipchuk", you would not be able to find a match since voter >> name
would read "Nastya" in the first iteration and "Osipchuk" in the next.
You can avoid the forward declaration if you move the searchname
function above main
.
Also read: Why is “using namespace std;” considered bad practice?