+ 2
is there a way to avoid crashes if a character is emtered in an int locaion?
I am tring some small projects for. Ow to get warmed up. I have an int variable but by accident sometimes a character is entered. Is there a way to avoid that?
24 Antworten
+ 9
@Immortal: Indeed!
+ 9
@Martin: Faith meant something like this:
https://code.sololearn.com/cPGkBUJ2B2GY/?ref=app
as for putting floats into ints.. where is the problem exactly? 😊
+ 9
@aklex. there is also stringstreams
+ 9
@martin.. is that a problem though? it wont crash the program. that is just user error
+ 8
int userInput;
cin >> userInput;
if(!cin) {
cin.ignore();
cin.clear();
cout << "that was not a number\n";
}
something like this 'should' work
faiths answer is probably better as it will get you used to error handling
+ 8
just put the try catch in a loop. it wont end the program when you raise/throw the error as it will be handled in catch.. (hint: you will need to add clear and ignore in the catch bit 😊 i will update the code to show this
+ 8
updated
+ 7
All languages have the built in abilities to raise and solve errors.
Python is:
try:
except:
finally:
C++ is
try{}
catch{}
finally{}
+ 7
i see! thanks!
+ 7
https://code.sololearn.com/cmN6QtO8dCCM/?ref=app
hows this? pretty sure it ticks all your boxes..
note: pretty much exactly what aklex did 😀
+ 6
? but it doesnt need to be edited for a second input. i will try it on pc...
try inputing this into the box
837 244
123.44
384
as it is a loop, it will continue prompting the user for the correct input. on here a single incorrect entry will be reentered forever or until timeout. on the pc it works as expected
837 244 error
123.44 error
384 correct. program ends
+ 4
Safe way of doing it, though you will get an exception if the input is too large, so you also have to use a try statement on stoi or check if it's too big:
#include <cctype>
bool verifyInput(const std::string& input)
{
for (auto& i : input)
{
//check if digit
if (!std::isdigit(i))
return false; //not a digit, return false
}
//input is numbers only
return true;
}
int main()
{
std::string input;
std::cin >> input;
if (verifyInput(input))
{
//input was valid, now we convert it to int
int goodinput = std::stoi(input);
}
}
+ 4
@Martin
Javascript has try catch 😜
@-
I think a better approach to checking if something is a float would just be to take the input as a float instead of a string.
Then, subtract it by the integer value, if it's equal to 0.0, the input can be taken as an integer then the stream can be cleared of all extra numbers.
Something like this:
https://code.sololearn.com/cebDG8afXwM0/?ref=app