如何将新的字符串名称与现有的txt文件进行比较

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

本文关键字:文件 txt 比较 字符串      更新时间:2023-10-16

我想在一个搜索名字的投票程序中实现一个简单的函数,如果这个名字已经存在,那么它将显示一条消息,表明一个人不能投票。但我对txt文件很困惑。下面的代码无法正常工作,我想了解我需要做什么。此外,如何找到全名?我认为它只是在搜索第一个单词

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;
} 
}
如果文件中的第一个名称与mainvoter不匹配,则返回false。代码中的注释和建议的更改:
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
}

其他注意事项:

  • 在检查文件中是否存在投票人的名称之前,请将该名称放入文件中。您需要首先检查该名称是否存在,并且只有当文件中存在而不存在时,才应将其添加到文件中。

  • 您使用getline读取投票人的姓名。getline允许空白字符,而用于从文件中读取的格式化输入voter >> name则不允许(默认情况下(。因此,如果您输入"Nastya-Osipchuk",您将无法找到匹配项,因为voter >> name在第一次迭代中会读取"Nastya",在下一次迭代中读取"Osipchu克"。

  • 如果将searchname函数移到main之上,则可以避免正向声明。

  • 另请阅读:为什么"使用命名空间std;"被认为是不好的做法?