0

Program crashes

So my teacher gave my an exercise: I should write a programm which displays a timetable after typing in the Numbers which are representing the subjects. But it crashes if anything but a number is entered. Any suggestions?

7th Feb 2019, 2:20 PM
Styouart
Styouart - avatar
6 Answers
+ 4
I'm guessing you are trying to input 'a' or something when using an integer. If invalid input is given then cin's failbit is set, you should check if this flag is set before continuing by using if( std::cin.fail() ) // handle error. You can also use if( !std::cin ) and you can even chain input and the check like if( !(std::cin >> n ) ). You can also combine that with a loop and only break out of it when the fail flag is not set. When the fail flag is set you also have to clear the flag before taking in new input by typing std::cin.clear(); Also there is a possibility for the user to type a string like "ajghakga", yes I'm very creative. So you need to clear that as well before taking any new input or you run into the same issue again, in order to do that you use std::cin.ignore( characters_to_ignore, ignore_until_this_char ) std::cin.ignore( 1000, '\n' ); would be sufficient but to make it more... idiot proof you should use std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ); which is a bit of a mouthful and you might have to #include <limits> for that one. That ignores the maximum amount of characters that can possibly be in the stream.
7th Feb 2019, 3:04 PM
Dennis
Dennis - avatar
+ 2
Alright, I edited it :) If you need an example, just ask.
7th Feb 2019, 3:11 PM
Dennis
Dennis - avatar
+ 2
int n; while( !(std::cin >> n) ) { // Entered if invalid input is given std::cin.clear(); std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ); } std::cout << n;
7th Feb 2019, 4:17 PM
Dennis
Dennis - avatar
0
This helped me a lot. When I'm at home, I'll try it right away. Thanks
7th Feb 2019, 3:06 PM
Styouart
Styouart - avatar
0
Umm.. can give an example of where I should put that in?
7th Feb 2019, 3:55 PM
Styouart
Styouart - avatar
0
Thanks
7th Feb 2019, 6:08 PM
Styouart
Styouart - avatar