【问题标题】:How to compare new string name with existing from txt file?如何将新字符串名称与 txt 文件中的现有字符串名称进行比较?
【发布时间】:2019-11-11 20:58:28
【问题描述】:

我想在一个正在搜索名字的投票程序中实现一个简单的函数,如果这个名字已经存在,那么它将显示一个人不能投票的消息。但是我对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;
         } 
 }

【问题讨论】:

  • 您的return 0 需要位于searchname 函数的末尾。不在 while 循环内。
  • 考虑如果文件中的第一个字符串不等于mainvoter,函数会做什么。匹配的字符串会被读取吗?

标签: c++ database fstream voting


【解决方案1】:

如果文件中的名字与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 &gt;&gt; name 不允许(默认情况下)。因此,如果您输入“Nastya Osipchuk”,您将无法找到匹配项,因为voter &gt;&gt; name 在第一次迭代中会读取“Nastya”,而在下一次迭代中会读取“Osipchuk”。

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

  • 另请阅读:Why is “using namespace std;” considered bad practice?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2022-01-06
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 2018-09-17
    相关资源
    最近更新 更多