比较指针和整数时编译器错误

时间:2016-07-24 22:54:03

标签: c++ arrays pointers

我正在尝试确保用户输入1到20之间的值,但是当我尝试编译代码时出现了这个编译错误:

  

错误:ISO C ++禁止指针和整数之间的比较

这是我的代码:

    #include <iostream>

using namespace std;

const int SIZE=20;

void bubbleSort(int numbers[], int SIZE);


int main()
{
    int numbers[SIZE]= {26, 45, 56, 12, 78, 74, 39, 22, 5, 90, 87, 32, 28, 11, 93, 62, 79, 53, 22, 51};
    int value=0;
    bool found;

    cout << "Today we are going to be searching for values." << endl;
    cout << "These are the values you have to choose from" << endl;

    for (int i=0; i<SIZE; i++)
        cout << numbers[i]<<"; ";


    cout << "What value would you like to search for?" << endl;

    cin >> value;

    do
    {
        cout << "Make sure to enter a value that's in the list." << endl;
        cin >> value;
        found=false;
        for (int i=0; i<SIZE; i++)
        {
            if (value==numbers[i])
            {
                found=true;
                break;
            }
        }
        if (!found)
            cout << "Enter a valid value !" << endl;
    }
    while (!found);

    bubbleSort(numbers, SIZE);



    return 0;
}

void bubbleSort (int numbers[], int SIZE)
{
    int maxElement=0;
    int index=0;


    cout << "Original order:" << endl;
    cout << numbers << endl;


    for(maxElement=SIZE-1; maxElement>=0; maxElement--)
    {
        for(index=0; index<=maxElement-1; index++)
        {
            if(numbers[index]>numbers[index+1])
            {
                swap(numbers[index], numbers[index+1]);
            }
        }
    }

}

void swap(int &a, int &b)
{
    int temp;
    temp=a;
    a=b;
    b=temp;

    cout << "Bubble Sorted:" << a << b << endl;
}

1 个答案:

答案 0 :(得分:1)

如果你想检查输入是否在1到20之间,那么写起来会更容易:

while(value<1 || value>20)
{
    cout << "The value chosen must be between 1 and 20." << endl;
    cin>> value;
}

如果要检查它的值是在放入数组的20个整数值的列表中,则只能将单个整数与数组进行比较。您必须在数组中搜索,例如使用find()

while(find(numbers, numbers+SIZE, value)==numbers+SIZE)
{
    cout << "The value chosen must be between in the list of authorized values" << endl;
    cin>> value;
}

顺便说一句,cout<<numbers将无法正常运作!要么创建一个for循环来遍历数字并显示所有数字,或者尝试:

copy (numbers, numbers+SIZE, ostream_interator<int>(cout,"; "));  

编辑:没有算法的替代方案

如果您不允许使用copy()find(),则必须使用for循环:

// for displaying 
for (int i=0; i<SIZE; i++)
    cout << numbers[i]<<"; "; 
cout <<endl; 

对于这个发现,你要么为它创建一个函数,要么你必须重新修改你的循环结构:

...
bool found; 
do {
      cin >> value;
      found=false; 
      for (int i=0; i<SIZE; i++) {
           if (value==numbers[i]) {
               found=true; 
               break; 
           }
       }
      if (!found) 
          cout << "Enter a valid value !" << endl;
} while (!found); 
...