2016-04-14 113 views
1

這是我的代碼:顯示1個結果與For循環

void IDsearch(vector<Weatherdata>temp) 
{ 
    int userinput; 
    cout << "Enter the ID of the Event and i will show you all other information: " << endl; 
    cin >> userinput; 
    for(unsigned int i = 0; i < temp.size();i++) 
    { 
     if(userinput == temp[i].eventID) 
     { 
      cout << "Location: " << temp[i].location << endl; 
      cout << "Begin Date: " << temp[i].begindate << endl; 
      cout << "Begin Time: " << temp[i].begintime << endl; 
      cout << "Event Type: " << temp[i].type << endl; 
      cout << "Death: " << temp[i].death << endl; 
      cout << "Injury: " << temp[i].injury << endl; 
      cout << "Property Damage: " << temp[i].damage << endl; 
      cout << "Latitude: " << temp[i].beginlat << endl; 
      cout << "Longitude: " << temp[i].beginlon << endl; 
     } 
    } 
} 

什麼即時試圖做的是通過所有的值的循環後,使之,如果userinput犯規匹配任何這些,那麼就打印out「它不匹配」一次。我知道如果我使用其他或如果(userinput!= temp [i] .eventID)它會顯示「它不匹配」多次。我是C++新手,請幫忙。謝謝

回答

3

如果找到某些元素,可以使用標誌來記住。

void IDsearch(const vector<Weatherdata>&temp) // use reference for better performance 
{ 
    int userinput; 
    bool found = false; 
    cout << "Enter the ID of the Event and i will show you all other information: " << endl; 
    cin >> userinput; 
    for(unsigned int i = 0; i < temp.size();i++) 
    { 
     if(userinput == temp[i].eventID) 
     { 
      cout << "Location: " << temp[i].location << endl; 
      cout << "Begin Date: " << temp[i].begindate << endl; 
      cout << "Begin Time: " << temp[i].begintime << endl; 
      cout << "Event Type: " << temp[i].type << endl; 
      cout << "Death: " << temp[i].death << endl; 
      cout << "Injury: " << temp[i].injury << endl; 
      cout << "Property Damage: " << temp[i].damage << endl; 
      cout << "Latitude: " << temp[i].beginlat << endl; 
      cout << "Longitude: " << temp[i].beginlon << endl; 
      found = true; 
     } 
    } 
    if(!found) 
    { 
     cout << "it doesnt match" << endl; 
    } 
} 
+0

非常感謝你:D。祝你有個美好的一天 – Ike

+0

你也可以''返回''而不是使用標誌。 –

+0

@Bob__ ...如果確保'temp'中沒有兩個元素具有相同的'eventID'。 – MikeCAT

1

一個很好的模式,「老天路」這樣做的:

int i; 
for (i=0; i<N; i++) 
    if (...) { 
    ... 
    break; // i does not reach N 
    } 

if (i == N) { // never entered ifs in the for loop 

的是,使用該標誌在其他的答案建議!我認爲它會對你有好處,知道這存在

0

還有另一種方法,它幾乎等同於在for循環中使用break語句。

只需遍歷矢量,然後在其外部打印結果即可。

unsigned int i = 0; 
for(; i < temp.size() && userinput != temp[i].eventID; ++i); 

if(i < temp.size() && userinput == temp[i].eventID) 
{ 
    cout << "Location: " << temp[i].location << endl; 
    cout << "Begin Date: " << temp[i].begindate << endl; 
    .... 
} 
else 
{ 
    cout << "it doesnt match" << endl; 
}