Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple C++ While loop not working

Tags:

c++

while-loop

I have a simple while loop i'm trying to implement but for the life of me can't figure out what I'm missing. I have currentuser initialized at the top to -1

while(currentuser = -1){
    cout << "Enter user ID: ";
    cin >> id;
    currentuser = search(a, length, id);
}

My search function is this:

int search (User a[ ], int length, string userID){
    User u;
    string tempid;
    int templegnth; //I ignore length for now as I will use it later
    for(int i=0; i<50; i++){
        tempid = a[i].getID();
        templegnth = tempid.length();
        if((tempid == userID)){
            return i;
        }
    }
    return -1;


}

I know its something very simple but the answer escapes me right now.

like image 611
Nick Avatar asked Dec 01 '22 07:12

Nick


2 Answers

The = (assignment) operator is not the same as the == (equality) operator.

The line :

while(currentuser = -1){

first assigns -1 to currentuser, and then checks if currentuser has a non-zero value. This will always be the case (-1 != 0), so the loop will never end.

You likely meant this instead :

while(currentuser == -1){

which compares currentuser to -1, and continues the loop as long as that comparison is true.

like image 149
Sander De Dycker Avatar answered Dec 06 '22 13:12

Sander De Dycker


You need to change:

while(currentuser = -1){

to be:

while(currentuser == -1){

Currently you are assigning currentuser to -1 every time your loop runs, rather than checking if it is still assigned to that value.

like image 22
thomasfedb Avatar answered Dec 06 '22 15:12

thomasfedb