搜索功能返回错误的结果

时间:2016-01-12 14:20:24

标签: c++11

我为我的程序创建了一个函数,它从文本文件中读取内容,将内容添加到矢量中,然后在该矢量中搜索。问题是,即使文件是空的,它表明它找到了一些东西,另一方面,如果我将返回值改为0,它根本不会给出结果!

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>

 using namespace std;

 vector<string> contacts;


 //This function returns at what index the name is found
  int searchContact(string contactToSearch) 
  {


   string entry;
   ifstream input;
   input.open("contacts.txt");

     while (input.good()) 
         {
             while (getline(input, entry))
                 {
                     contacts.push_back(entry);

                 }
             input.close();
         }

   for(int i = 0; i < contacts.size(); i++) 
     {

         if(contactToSearch == contacts[i]) 
             {
         //Found => Returning index rest of program can see index
         return i;
            }
      }

      return 1;
     }

1 个答案:

答案 0 :(得分:0)

我刚刚重构了你的代码。可以进一步改进,但首先是

1)你不需要一段时间来输入input.good()

2)你试图返回0和1,它们确实是有效位置,其中字符串可能存在于向量中

除此之外,我仍然认为您的代码可能无法正确填充数组。原因可能是: - 区分大小写,读取错误文件,二进制文件等等。

以下是您可以使用的重构代码

#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>

using namespace std;

void readContacts(const string &fileName inputFileName, vector<string> &contacts){
    string entry;
    ifstream input;
    input.open(inputFileName);
    if (input.good())
    {
        while (getline(input, entry))
            contacts.push_back(entry);
        input.close();
    }
}

int searchContact(const string &contactToSearch, vector<string> &contacts)
{
    for (int i = 0; i < contacts.size(); i++)
    {
        if (contactToSearch == contacts[i])
            return i;       
    }
    return -1;
}

int main(){
    vector<string> contacts;
    // This needs to be filled in with the contact name u want to search
    string contactToSearch;
    readContacts("contacts.txt", contacts);
    int index = searchContact(contactToSearch, contacts)
        if (index != -1)
            cout << "Found Contact " << contactToSearch" at location " << index << endl;
        else
            cout << "Could Not find contact " << contactToSearch << endl;
}