首页 > 解决方案 > 如何将新字符串名称与 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;
         } 
 }

标签: c++databasefstreamvoting

解决方案


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

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


推荐阅读