Hello! I have a problem with being able to take care of run-time errors where the user types in data different than the one expected. For example, an integer is expected, but (maybe) the user enters a string. In my console programs, when this happens, I just get a whole lot of junk printed on my screen. How can I take care of this, such that an error message is displayed when this happens, instead of the whole program going to trash? Please, I need help urgently!
Here it is: Code: #include <iostream> using namespace std; int main() { try { cout << "Please enter the number of values in the Fibonacci series that you want: "; int n; cin >> n; n = static_cast<int>(n); if (n < 1) throw "You dey craze?!\nIn fact, I don vex!\nBye bye [:-(]"; if (n == 1) cout << "The series is as follows: " << 1; else { int p = 1, pp = 0, w; cout << "\nThe series is as follows: "; for (int i = 0; i < n; i++) if(i%2 == 0) { p = p + pp; cout << p << " "; } else { pp = pp + p; cout << pp << " "; } } } catch (const char aMessage[]) { cout << endl << aMessage << endl; } return 0; } Well, when any number is typed, the fibonacci series is produced to that nth number. However, if a string, or a character is entered, the program begins to flood the screen with some junk output continuously, and does not end, unless forced to. What can i do?
sir we know that characters are stored as integers when u enter a character it will go for its corresponding ascii value and it will proceed further use ctrl+pause/break in keyboard to come for junk output
Yeah, I know, but if you look at the code, you will find out that I used the try-throw-catch method to take care of the case where the user enters a negative number. Now, what I want is a method to, instead of leaving the program to go into an infinite loop, display an error message and then, maybe resume, or end the program.
Try it... Code: #include<iostream.h> #include<string.h> #include<conio.h> main() { int n; cout << "Please enter the number of values in the Fibonacci series that you want: "; cin >> n; if(!isdigit(y)) cout << "It's a string,please enter a number"; cout << '\n'; getch(); }
Try it... Code: #include<iostream.h> #include<string.h> #include<conio.h> main() { int n; cout << "Please enter the number of values in the Fibonacci series that you want: "; cin >> n; if(!isdigit(y)) cout << "It's a string,please enter a number"; cout << '\n'; getch(); }
how about preventing a stream error? Code: #include <iostream> #include <sstream> #include <string> int main() { std::string input; std::istringstream ss; int num; do { num = -1; std::cout << "Enter positive number: "; std::cin >> input; ss.clear(); ss.str(input); if(!(ss >> num)) std::cout << "garbage input: " << input << "\n"; } while(num < 0); while(std::cin.get() != '\n') ; std::cout << "num = " << num; std::cin.get(); return 0; }