如何将新的字符串名称与现有的txt文件进行比较
How to compare new string name with existing from txt file?
我想在一个搜索名字的投票程序中实现一个简单的函数,如果这个名字已经存在,那么它将显示一条消息,表明一个人不能投票。但我对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;"被认为是不好的做法?
相关文章:
- 如何将 txt 文件中的行分隔为组件C++
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 一种在C++中读取TXT配置文件的简单方法
- 无法打开.txt文件
- 如何使用CLion在Mac上创建一个新的.txt文件
- 我可以读取静态对象中的文件.txt吗?C++
- C++-需要读取存储在文件(.txt)中的时间戳并正确检索
- 具有文件.txt的 C++ 中的设置
- 如何在 CMakeList 中包含 h/hpp 头文件.txt而不是 cpp 或其他 hpp 文件
- 使用函数读取文件.txt中的矩阵
- 任何人都知道如何解决尝试将从MySQL数据库返回的行打印到文本文件(.txt)中的C++
- 读取文件.txt C
- 为什么我的方法不从文件.txt中读取float类型
- 如何读取名称(仅文件.txt)作为参数传递的文件(在任何目录中)?C++
- 读取文件".txt"并将每行的数据分配给循环列表中的新节点C++
- 如何用C++将字符串文件Txt解析成数组
- 如何在c++中读取和编辑文件txt
- 从文件.txt读取字符串数组并使用它来玩康威的生命游戏
- 导入文件txt时出错
- 如何仅读取文件.txt中的数字