New to c++ and getting an error for searching an Array
I am getting an error and I can't figure out what I am doing wrong. I have compared to similar code in the text book and I am still over looking something any help with what I am missing would be appreciated!
Error 1 error C2109: subscript requires array or pointer type 45 1
PHP Code:
#include "stdafx.h"
#include <conio.h>
#include <iostream>
using namespace std;
//Function prototype
int searchList (const int [ ], int);
//constant
const int NUM_ELEMS = 10;
int main()
{
// varibles
int luckyNumbers [NUM_ELEMS] = {13579, 26791, 26792, 33445, 55555, 62483, 77777, 7422, 85647,
93121};
// call the LuckyNumbers check function
searchList (luckyNumbers, NUM_ELEMS);
_getche ();
return 0;
}
// ***************************************************
// The searchList function performs a linear search on the int array
// luckyNumbers. If the number is with in luckyNumbers it will return
// message confirming the numbers are winners otherwise it it will
// notify user that the numbers are not winning numbers
// ***************************************************
void searchList (int luckyNumbers[], int NUM_ELEMS)
{
int winningNumbers = 0;
bool found = false;
cout << "Enter this weeks Winning Numbers: " << endl;
cin >> winningNumbers;
for (int i = 0; i < NUM_ELEMS; i++)
{
if (luckyNumbers[i] == winningNumbers)
{
found = true;
break;
}
}
if (found)
{
cout << "You are a winner! " << endl;
}
else
{
cout << "Sorry better luck next week. /n ";
}
}
Re: New to c++ and getting an error for searching an Array
The problem is using your const int NUM_ELEMS as the name of your function parameter. Call it something else, or better yet don't pass it at all as it's global.
Re: New to c++ and getting an error for searching an Array
To correctly use code tags with c/c++ code rather than use PHP tags, Go Advanced, select the code and click '#'.
Re: New to c++ and getting an error for searching an Array
Your searchList() declaration has the const int [] as the first argument - but for the definiton it is int [].
As the contents of the array luckyNumbers are not intended to be changed, it would be better to define the array as const.
To output a new line within a string literal you use \n and not /n.
Also, it would be considered a better design to split the operations of obtaining a number and searching for it into separate functions rather than having both these operations within the same function. The search function could then take as an argument the number to find and return a bool true or false which the calling function (or a message function) could then use to determine which message to display. Your search function is then more general which could be reused.