I'm trying to program a really simple RPG with my friend from work based on this game we play there leveling him up. In my "main.cpp" I have the person enter their name and the std::getline handles it fine and outputs it correctly. However, when my program get's to the line where it asks for your inventory item, it doesn't give me an option to enter it and it just goes directly to the "calculating current stats" output. I don't understand what I'm doing wrong because I set it up the exact way as when the user enters their name earlier and that one works correctly. Any help would be greatly appreciated thanks!
A "std::getline()" followed by "std::cin >>" works just fine, but "std::cin >>" followed by a "std::getline()" does not work well because the "std::cin >>" will leave the new line character in the input buffer that the getline will extract and move on with out waiting for any input from the user. As Mange showed you this is a way to clear up the problem, but I would suggest std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>. as std::cin.ignore(); may only ignore one character and this may not be enough. Although in some cases it does work.
Any "std::getline()" that is preceded by a "std::cin >>" needs the use of "std::cin.ignore(...)" to clear the input buffer to work properly.
In general, I think std::cin.ignore() belongs after std::cin>> rather than before std::getline().
The reason I think so is because it's not always easy to know if you need to use std::cin.ignore() before std::getline(). It depends on what input operation was used previously. If you use std::getline() at the beginning of a function, or after a loop that use std::cin>>, you can easily end up in situations where std::cin.ignore() is sometimes the right thing to do and sometimes it isn't but you have no way of telling.
If you say that any piece of code that reads input is responsible for reading the whole line it becomes much easier to write correct code. You no longer need to worry about doing anything special before using std::getline(), but it does mean you will have to use std::cin.ignore() after std::cin>>. If you use std::cin>> many times in a row it's probably a bit overkill to use std::cin.ignore() each time, but at least use it at the end of functions and in other situations where you are not sure what the next input operation is going to be.
Well in this case the use of std::cin.ignore() works fine because the last entry was a double value and not a string. So there is not a lot of junk needing to be cleared from the buffer.
@Peter87, you make a good point so for better readability your placement is correct.
@Symphoneee, we have decided this is how it should go...