2016-08-15 111 views
-2

我試圖比較一個字符串的字符數與數組的索引元素,但我有麻煩。 例如,如果userInput等於XX,輸出應該是:比較字符串和數組C++

XX不是陣列中的位置0

XX是在位置陣列1

XX不處於陣列在位置2.

arr[] = {"X", "XX", "XXX"}; 
string userInput; 
cin >> userInput; 

    for (int i = 0; i < userInput.length(); i++) 
{ 
    if (userInput[i] == arr[i]) 
    { 
     cout << userInput << " is in the array at position " << i << endl; 
    } 
    else 
    { 
     cout << userInput << " is not in the array at position " << i << endl; 

我收到此錯誤,我不知道如何解決它。我相當新的編程,所以任何幫助將是偉大的。謝謝。

無效的操作數的二進制表達式( 'INT' 和 '字串'(又名 'basic_string的,分配器>'))

+0

對不起,應該提到。我有:使用命名空間標準;在我的代碼的開始。 – Mludbey

+1

@Mludbey解決此類問題的正確工具是使用您的調試器,但在此之前不要詢問Stack Overflow。告訴我們您在檢查您的代碼時所做的所有觀察。您也可以閱讀[**如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)**] At最少給我們留下一個** [MCVE] **,它可以再現您的問題。 (這是個人評論,由πάνταῥεῖ™提供) –

+0

對不起,我錯誤地讀了你的程序並對其進行了解釋。你有'arr []'在開始時沒有任何類型,這使我走錯了路。這是'字符串arr []'?如果是這樣,你只需要說'if(userInput == arr [i])'而不是你所擁有的。 –

回答

1
arr[] = {"X", "XX", "XXX"}; 

假設上述陣列被定義爲字符串。

cin >> userInput; 

必須由

getline(cin,userInput) 

代替作爲userInput是字符串。條件語句

if (userInput[i] == arr[i]) 

應與

if (userInput == arr[i]) 

否則,你會被比較字符串的字符userInput的指數來代替我

最後,作爲一個整體,這是你的代碼應該怎麼看

string arr[] = {"X", "XX", "XXX"}; 

string userInput; 
getline(cin,userInput); 
for (int i = 0; i < userInput.length(); i++) 
{ 
    if (userInput == arr[i]) 
    { 
     cout << userInput << " is in the array at position " << i << endl; 
    } 
    else 
    { 
     cout << userInput << " is not in the array at position " << i << endl; 
    } 
} 
1

你的問題是,你是比較每個字符數組中每個字符串的輸入。​​給你字符userInput的位置i(從0開始);而arr[i]給出字符串arr的位置i(也從0開始)。如果您不小心嘗試訪問不存在的arr[3],您還會得到另一個錯誤(即使它有效)。使用此代替:

#include <iostream> 
#include <string>  // Used for std::getline() 

// Don't use 'namespace std' - it's bad practice 

int main() 
{ 
    int arrSize = 3; // Now we know the size of the array, we won't exceed arr[2] 
    std::string arr[3] = { "X", "XX", "XXX" }; 
    std::string input; 

    std::cout << "Enter input: "; // A propmt would be useful 
    std::getline(std::cin, input); // Much better way to get input 

    for (unsigned int i = 0; i < arrSize; ++i) // Now we won't exceed the array size 
    { 
     if (input == arr[i]) // Compare the input string (not character) with each string in arr[] 
      std::cout << "Your input is at position " << i << std::endl; 
     else 
      std::cout << "Your input is not at position " << i << std::endl; 
    } 

    std::cin.ignore();  // Wait for user to press enter before exiting 
    return 0; 
} 
+0

這很有幫助,但我想比較輸入字符和數組字符串。例如,如果輸入= XXXLM,我希望它讀取到XXX並忽略LM – Mludbey

+0

@Mludbey您應該在問題開始時非常明確地表達。就目前而言,你想要比較的東西並不十分清楚。 –

+0

@Mludbey你也不清楚爲什麼你要忽略LM而不是XLM或XXLM或者只是M. –