hatinacat2000
hatinacat2000

Reputation: 145

C++ if statement using lambda expression returns true but output is from false, why

I am using C++ 17 on a Windows 10 OS using a Visual Studio 2017 compiler.

I am trying to set up a menu system with do-while loops and user input (always a huge pain a year later). When I do these, I put an admonishment in an "else" statement if input was not of the correct type.

I ran this code thinking it would either die before it started or run perfectly, but got surprised when I entered the number 2 for the input in the itemMenu() function and got immediately kicked into that function's else statment. I did some debugging and confirmed that the if statements were all returning true. So how am I getting to the else statement instead?

I am using a lambda expression for the critical if statement and tested that the value of f, and in fact the if statement, is true. I do not regularly use these and I get weird notices about it during debug:

Menu.cpp
<...>\menu.cpp(94): warning C4805: '==': unsafe mix of type 'int' and type 'bool' in operation
<...>\menu.cpp(97): warning C4805: '==': unsafe mix of type 'int' and type 'bool' in operation
<...>\menu.cpp(86): warning C4715: '<lambda_6de01b1fefb73a14272db9ac7503c22b>::operator()': not all control paths return a value
<...>\Desktop\startingOver\Debug\startingOver.exe

That sounds like maybe my lambda expression is the problem, but more likely it is the cin flags needing to be cleared. I tried that too (perhaps incorrectly) and it did not solve the problem. What could be wrong? Here is my code:

//Menu.h
#pragma once
#include <iostream>
#include <string>
#include "Player.h"
#include "Item.h"
#include "MoveCommand.h"
using namespace std;

class Menu
{
public:
    Menu();
    ~Menu();

    static void mainMenu(Player * player);
    static void itemMenu(Player * player);
    static void hud(Player * player);
};

and

//Menu.cpp
#include "Menu.h"

Menu::Menu()
{
}

Menu::~Menu()
{
}

void Menu::mainMenu(Player * player)
{
    char input;
    // do and keep doing while input is bad
    do {
        cout << "What to do? (W: go north; S: go south; A: go west: D: go east; I: inventory  ";
        cin >> input;

        if (toupper(input) == 'W')
        {
            MoveCommand * cmd = new MoveCommand(0, -1);
            break;
        }
        else if (toupper(input) == 'S')
        {
            MoveCommand * cmd = new MoveCommand(0, 1);
            break;
        }
        else if (toupper(input) == 'A')
        {
            MoveCommand * cmd = new MoveCommand(-1, 0);
            break;
        }
        else if (toupper(input) == 'D')
        {
            MoveCommand * cmd = new MoveCommand(1, 0);
            break;
        }
        else if (toupper(input) == 'I')
        {
            itemMenu(player);
            break;
        }
        else {
            cout << "Not an option, enter another input...  " << endl;
            system("pause");
        }

        system("CLS");

    } while (toupper(input) != 'W' && 
        toupper(input) != 'S' && 
        toupper(input) != 'A' && 
        toupper(input) != 'D' && 
        toupper(input) != 'I');

    system("cls");
}

void Menu::itemMenu(Player * player)
{
    //All this first part does is draw a figure on the screen:
    //----------------------------------------------
    cout << "INVENTORY: " << endl;

    for (int i = 0; i < 10; i++)
    {
        // if inventory location is null:
        if (player->inventory[i], NULL) {
            cout << "[   ]";
        }
        else
            cout << "[ i ]";
    }
    cout << endl;

    for (int i = 1; i <= 10; i++) cout << "  " << i << "  ";
    cout << endl;
    //------------------------------------------------
    char input;

    // I made this lambda function to facilitate the test the user input is a digit from 1 to 10.
    // it is possible that this is a problem, even though debug says this value returns true (see note/test below)
    auto f = [](char in) {for (int i = 1; i <= 10; i++) {
        if (in == i) return true;
        else
            return false;
    }};

    // do and keep doing until choice is to quit
    do {
        cout << "Pick a slot: (Enter a number 1:10, or 'Q' to exit.  ";
        cin >> input;

        if (toupper(input) == 'Q') break;
        //bool both = (isdigit(input) == true && f(input) == true); // testing if value, which is true in debug tests...
        // ... and yet we never see anything inside this block--I even did a pause, which works everywhere else, but
        // the program is jumping to the else (wrong input) statment
        if (isdigit(input) == true && f(input) == true) {
            cout << "succesfully accessed " << input << "th inventory item" << endl;
            system("pause");
        }

        else
            cout << "(Inventory Else) Not an option, enter another input..." << endl; // I appended (Inventory Else) to confirm we go here
        system("pause");
        system("cls");

    } while (toupper(input) != 'Q' && f(input) == false);
    system("cls");
}

void Menu::hud(Player * player)
{
}

and

//Main.cpp
#pragma once
#include <iostream>
#include <string>
#include "Player.h"
#include "Command.h"
#include "MoveCommand.h"
#include "Event.h"
#include "Item.h"
#include "Tile.h"
#include "Menu.h"

int main() {

    Player player;

    //game loop
    while (1) {
        Menu::mainMenu(&player);
    }

    return 0;
}

EDIT: and I forgot this important piece of the puzzle:

//Player.h

class Player
{
private:
    int _x;
    int _y; 
public:
    Item *inventory[10];

    Player();
    //~Player();

    //methods
    int getX();
    int getY();
    void move(int x, int y);
};

Please note that if I am supposed to know a better way to do anything (like regex or try/throw/catch or anything else) I would rather if I were confident that I knew how.

Upvotes: 0

Views: 1740

Answers (1)

MSalters
MSalters

Reputation: 179981

It appears that you are mixing 0 and '0'. That is to say, the value 0 and the character 0. The first is an int, the second is a char. C++ will do some conversions, so '0'+2 == '2', but importantly '0'+'2' != '2'.

Therefore, the loop in your lambda should run from char i = '0' to i <= '9'. Not that it really matters here. You missed out on std::isdigit(c).

Your other problem is isdigit(input) == true. This is an anti-pattern. In C++, you don't compare against booleans. And it can fail spectacularly for isdigit(c), which returns a non-zero number when c is a digit. It's very well possible that isdigit('5') returns '5', and isdigit('0') returns '0'. Yes, I said a non-zero number, but '0' is a non-zero number. isdigit('C') will always return 0 (the number, not the character).

Upvotes: 3

Related Questions