Problem with If in Loop to produce Error

I need to create a program validates a code input. If the code is invalid an error should be displayed, otherwise nothing would happen.

The program works with valid input but not with invalid input.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>
using namespace std;

int main( )
{
    //declare and initialize variables
	string pkgCode = " ";
	string pkgcodeArray[5] = {"BB", "SP", "NP", "HE", "UC"};
	int searchIndex = 0;


	cout << "Please, input the package code:"<<endl;
	cin >> pkgCode;
 
	//validate input with loop
	  while (pkgCode != pkgcodeArray[searchIndex])
       {
		 searchIndex++;
			 if (searchIndex > 5 && pkgCode != pkgcodeArray[searchIndex])
				{
				 cout <<  "ERROR: Package Code does not exist. Please, check and re-enter." <<endl;
				  }//end if
	  }//end loop

    system("pause");
    return 0;
} //end of main 
Last edited on
First are you sure using && ? The code will run if both condition is true
then are you sure for not using break; ?
I tried to change it to this but it's still working working
1
2
3
4
5
6
7
8
9
10
	//validate input with loop
	  while (pkgCode != pkgcodeArray[searchIndex])
       {
		 searchIndex++;
			 if (searchIndex > 5)
				{
				 cout <<  "ERROR: Package Code does not exist. Please, check and re-enter." <<endl;
				 break;
				 }//end if
       }//end loop 
Last edited on
searchIndex > 5 that means its check if searchIndex is more or same as 6
and i think increment should place on bottom loop, because searchIndex will increase before checking
I did try that, but it is still not displaying the cout statement.
Try to change >5 to >=5 array index number start from 0 so last index is n-1
or change to for loop
Not working either and the for loop has me way worse off than I was before.
Topic archived. No new replies allowed.