2016-09-03 46 views
-5
#include <iostream> 
#include <Windows.h> 
#include <string> 
using namespace std; 



int main(){ 
    string Whitelist[4] = {"Stian", "Mathias", "Modaser"}; 
    for (int x = 0; x < 3; x++){ 
     cout << x + 1<< ". " << Whitelist[x] << endl; 
     if (Whitelist[x] == "Stian" && "Mathias" && "Modaser"){ 
      cout << "" << Whitelist[x] << " is here" << endl; 
     } 
     else{ cout << "no one is here" << endl; } 
    } 
    cin.get(); 
    return 0; 
} 

//所以耶基本上我只是試圖循環通過我的數組,看看有沒有這些名稱。所以我猜你幾乎可以閱讀代碼所做的事情,因爲你大部分都是優點:P。但是當我問我的朋友,誰已經編了1-2年的編碼時,他說我不能像這樣循環數組,並告訴我使用矢量。他是什麼意思?和我的代碼的作品?這是循環訪問數組的正確方法嗎?

+1

'Whitelist [x] ==「Stian」&&「Mathias」&&「Modaser」'不會做你認爲它的作用。 – Biffen

+1

他們的意思是你應該使用'std :: vector Whitelist = {「Stian」,「Mathias」,「Modaser」};'。聽他們說。 –

+0

好的,但你可以向我解釋它是什麼,我很新的編程:P – manplox0

回答

0

這組編碼是錯誤的

if (Whitelist[x] == "Stian" && "Mathias" && "Modaser"){ 
    cout << "" << Whitelist[x] << " is here" << endl; 
} 

爲什麼?因爲假設的第一個條件if語句的計算結果爲true這樣的:

if (true && "Mathias" && "Modaser") 
{ 
    //... 
} 

然後代碼就沒有意義。在if語句,你必須單獨檢查每個條件,像這樣:

if (Whitelist[x] == "Stian" && Whitelist[x] =="Mathias" && Whitelist[x] =="Modaser"){ 
    cout << "" << Whitelist[x] << " is here" << endl; 
} 

但是,由於任何1串不能在同一時間三個名字,這種情況下會失敗,(你使用&&)。修正了使用||操作,這樣你的代碼,爲您的最終代碼(另外,除去<< "",這僅僅是多餘的,不必要的):

if (Whitelist[x] == "Stian" || Whitelist[x] =="Mathias" || Whitelist[x] =="Modaser"){ 
    cout << Whitelist[x] << " is here" << endl; 
} 

BTW:作爲一個建議,使用std::vector<std::string>,不是裸數組,所以你比數組更容易和更多的功能。 最後,你的數組中還有4個元素,其中一個未使用。這可能是一個錯字,因此請將您的數組大小設置爲3

+1

什麼是''「'? –

+0

@LightnessRacesinOrbit固定 –

+2

_「這只是多餘的,不必要的」_LOL,故意? ;) –

0

像這樣循環數組沒有什麼根本性的錯誤。

我們只能猜測你的朋友的意思,但我可以執行我自己的代碼審查。

但是,你有四個數組元素,只能循環其中三個,這可能是一個錯誤;如果是這樣,那麼證明你最好使用迭代器,而不是對可能出錯的硬編碼數字。

此外,您的if有條件是錯誤的:您的意思是||(「或」),而不是&&(「和」)?而且你必須完全寫出來的鄰接條件,所以:

if (Whitelist[x] == "Stian" || Whitelist[x] =="Mathias" || Whitelist[x] =="Modaser") 

我不知道爲什麼你對所有這些值進行比較,當他們的陣中唯一的。那麼,除了那個空的第四個元素,也許你正試圖抓住這一點。我們不知道,因爲你沒有告訴我們。你的意思是搜索Whitelist而迭代一些其他數組?我們無法知道。也許這就是你的朋友真的的意思?再次,我不能說。

""std::cout只是等待資源,沒有字面意思。去掉它。最後,有點切線,it would be better not to block waiting for input as a means to keep your console window open。這不是你的計劃的工作。

相關問題