2016-08-15 113 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. –