2016-04-14 6 views
1

のために1件の検索結果を表示:これは私のコードでループ

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; 
     } 
    } 
} 

何イム値のすべてをループした後にそれを作るためにあるやろうとし、それらのいずれかとユーザ入力のdoesntの試合、そしてちょうど印刷する場合「それは一度もマッチしません」。私はelseを使うのか知っているのか(userinput!= temp [i] .eventID)、それは "それはdoesntの一致"を何度も表示するだろう。私は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

ありがとうございます。良い一日を持っています – Ike

+0

また、フラグを使用する代わりに 'if'から' return'することもできます。 –

+0

@Bob__ ...もし 'temp'の中の2つの要素が同じ' 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; 
}  
関連する問題