2016-06-01 53 views
-6

這裏是我的一小段代碼我在哪裏卡住了。我希望代碼保持提示用戶搜索名稱,即使找到了。因此,我的代碼中的中斷將無法工作。我的代碼有缺陷,因爲每次for循環達到一個小於我的矢量大小時,它會打印出「找不到名稱!」 這就是我說的,但我不能想出一個辦法來解決這個問題。我發現堆棧上的其他帖子,並在我的代碼中嘗試過,但他們不工作。C++打印出「未找到」的消息只有一次

do 
{ 
    cout <<"Enter name for search: "; 
    cin >> name; 

    for (int i = 0; i < pvector.size(); i++) 
    { 
     if (pvector[i]->fName == name || pvector[i]->lName == name) 
     { 
      cout << pvector[i]->fName << " "<< pvector[i] ->lName <<" "<<"username:"<< pvector[i]->userName <<" "<<"password:" << pvector[i]->pword <<endl; 
     }else if(i == pvector.size()-1) 
     { 
      cout << name <<" "<<"not found!" << endl; 
     } 
    } 
} while (cin.good()); 
+0

沒關係,我正在讀「pvector」爲「指針向量」而不是「指針結構的載體」(可能命名爲「個人資料」基於關閉的OP以前的帖子。) – NonCreature0714

+0

請提供[一個最小的,完整的和可驗證的例子](http://stackoverflow.com/help/mcve)。 –

+0

這可以通過使用調試器輕鬆解決。 –

回答

0

你缺少休息,一旦你找到一個匹配,這個工程就在我身邊:

#include "stdafx.h" 

#include <iostream> 
#include <vector> 
#include <string> 


using namespace std; 

int main() 
{ 
    std::vector<std::string> pvector; 
    pvector.push_back("Steve"); 
    pvector.push_back("Jhon"); 
    pvector.push_back("Michael"); 

    char name[256]; 

    do 
    { 
     cout << "Enter name for search: "; 
     cin >> name; 

     for (int i = 0; i < pvector.size(); i++) 
     { 
      if (pvector[i] == name) 
      { 
       cout << pvector[i] << " found" << endl; 
       break; 
      } 
      else if (i == pvector.size() - 1) 
      { 
       cout << name << " " << "not found!" << endl; 
      } 
     } 
    } while (cin.good()); 
} 
+0

此代碼的工作,但我遇到了一個問題,如果我有多個名稱,並希望把它們打印出來,只打印出它找到的第一個。我認爲這是因爲休息。我將如何能夠打印出矢量中找到的所有名字? –

+0

只要保持找到該名字的時間數量的計數器。如果計數器在到達矢量的末尾時仍然處於0,則只輸出「未找到」。 –

0

的名字被您pvector發現後,你應該打破迴路的電流,這意味着下面的代碼

cout <<"Enter name for search: "; 
cin >> name; 

for (int i = 0; i < pvector.size(); i++) 
{ 
    if (pvector[i]->fName == name || pvector[i]->lName == name) 
    { 
     cout << pvector[i]->fName << " "<< pvector[i] ->lName <<" "<<"username:"<< pvector[i]->userName <<" "<<"password:" << pvector[i]->pword <<endl; 
     break; // add a break here 
    }else if(i == pvector.size()-1) 
    { 
     cout << name <<" "<<"not found!" << endl; 
    } 
} 

突破上面添加只會打破目前for循環,並繼續進行休息do ... while