#when i std::cin a int and input a letter it will give me the digit 2?

30 messages · Page 1 of 1 (latest)

sullen needle
#

can someone explain me why my cin alway gives me a 2 and not like a error? I try to make a inventory remove function and when i input a letter it will remove my item on ID 2.

real turtleBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

sullen needle
#
void Inventory::remove_item(int _item_id) {
    std::istringstream iss(std::to_string(_item_id));
    int id;
    if (!(iss >> id)) {
        std::cerr << "Invalid input. Please enter a valid item ID." << std::endl;
        return;
    }

    for (auto it = inventory.begin(); it != inventory.end(); ++it) {
        if ((*it)->get_id() == _item_id) {
            inventory.erase(it);
            std::cout << "Item removed." << std::endl;
            return;
        }
    }

    std::cout << "Item with ID " << _item_id << " not found in inventory." << std::endl;
}
#
else if (choice == 2) {
                                int rm;
                                std::cout << "What item do you want to remove?\nID > ";
                                std::cin >> rm;
                                user_inventory.remove_item(choice);
                                pressEnterToContinue();
grizzled grotto
#

Look at what you're passing to remove_item.

sullen needle
#

ive tried now if (isdigit(id)) {} but now it always dont see my id as a digit

#

i dont understand

grizzled grotto
#

isdigit checks a character, int is already a number.

sullen needle
#

please dont give me the final answer. i want to solve it ^^

sullen needle
#

is it maybe because of cpp std::istringstream iss(std::to_string(_item_id));?

grizzled grotto
#

No.

#

When you do stream >> anInt either it takes an int or it fails totally.

#

The best approach to account for invalid inputs are to take them as strings then check if they represent numbers.

sullen needle
#

i see the issue i think

#
for (auto it = inventory.begin(); it != inventory.end(); ++it) {
#

because of my autp maybe

#

but i dont know how to do it correctly

grizzled grotto
#

Well what are you trying to do?

sullen needle
#

lemme think

#

hmm

#

can i get a tipp? :)

#

i tried: ```cpp

int it;

for (int it = ...)

for(auto it = inventory.begin(); it != inventory.end(); ++it){
if it;
}

for (auto it = inventory.begin(); it != inventory.end();) {
if ((*it)->get_id() == _item_id) {
...
} else {
++it;
}

#

but i think im on the wrong road to solve the problem

#

oh my

#

i see it i think

#

is the solution that it increases with the forloop and I and the id also increases with the forloop?

#

no

#

have it

#

!close