Hello, I made that my code sends a message whenever it isn't any of options, it works with numbers but whenever it is letter is just goes crazy. Could anyone help me solve this problem? I am pretty beginner with c++ and this error shouldn't be a big deal to spot out I think...
#Weird thing happens whenever I type a letter
24 messages · Page 1 of 1 (latest)
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.
you are not updating odpowiedz inside the loop of the else block
so what is happening is that when
std::cin >> float fails, it doesn't read anything then sets some flags in std::cin that says "hey there is an error".
If there is an error flag, std::cin will not read any new data until the error is cleared
So as a result, it will just constantly loop the same input and not doing anything
uh it sounds complicated
you can do cin.clear() to clear any errors, then cin.ignore to ignore the character until a new line. here is an example
#include <iostream>
#include <limits>
#include <sstream>
constexpr auto max_size = std::numeric_limits<std::streamsize>::max();
int main()
{
std::istringstream input("1\n"
"some non-numeric input\n"
"2\n");
for (;;)
{
int n;
input >> n;
if (input.eof() || input.bad())
break;
else if (input.fail())
{
input.clear(); // unset failbit
input.ignore(max_size, '\n'); // skip bad input
}
else
std::cout << n << '\n';
}
}
is there any simplier way...?
Don't input bad inputs :)
Joking aside, there is an option to have cin raise an exception on bad inputs. That is an alternative, though I'm not a fan
and what is that option?
because if I will use complicated stuff as beginner my teacher will suspect some stuff
float wartosc_a()
{
float a;
cin >> a;
while (!cin)
{
cin.clear();
cin.ignore((unsigned)-1, '\n');
cout << "a nie moze byc mniejsze lub rowne 0, podaj nowa wartosc" << endl;
cin >> a;
}
return a;
}
So this is the non exception version
Here is the exception example
#include <fstream>
#include <iostream>
int main()
{
int ivalue;
try {
std::cin.exceptions(std::ifstream::failbit); // may throw
std::cin >> ivalue; // may throw
} catch (const std::ios_base::failure& fail) {
// handle exception here
std::cout << fail.what() << '\n';
}
}