c++ - 如何将新字符串名称与 txt 文件中的现有字符串名称进行比较?
问题描述
我想在一个正在搜索名字的投票程序中实现一个简单的函数,如果这个名字已经存在,那么它将显示一个人不能投票的消息。但是我对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;
}
}
解决方案
false
如果文件中的名字不匹配,则返回mainvoter
。带有建议更改的代码注释:
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”,而在下一次迭代中会读到“Osipchuk”。searchname
如果你移动上面的函数,你可以避免前向声明main
。
推荐阅读
- c++ - 如何打印大于“unsigned long long”的“std::bitset”的十进制值?
- java - 使用参数化测试返回方法应该没有参数
- java - 如何根据文本视图的长度对齐文本视图
- reactjs - 如何在前端 React JS 上控制用户角色 - MERN 应用程序
- bash - 如何针对 mariaDB docker 容器运行 sql 脚本
- security - Prometheus Pushgateway 的访问控制
- google-cloud-platform - 使用 gsutil ls 在特定子目录中查找特定文件名
- angularjs - CORS 不适用于 Heroku,但可以在本地使用 Node js
- java - 从方法 addTwo 返回长数组 (a) 元素的索引
- python - friendCount 没有打印预期的输出