| | |
Avoid PROGRAM CRASH
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: Mar 2006
Posts: 5
Reputation:
Solved Threads: 0
Absolutely right! Here the source code:
#include <iostream.h>
#include <limits.h>
main()
{
int n; /* number of values entered */
cout << "How many values? (1..10) -> ";
cin >> n;
cin.ignore(SHRT_MAX, '\n');
/* control number of value entered by the user */
while (n<1||n>10)
{
cout << "\nInvalid input. Try again (1..10) -> ";
cin >> n;
cin.ignore(SHRT_MAX, '\n');
}
}
Thus so far I have got the input will be within the range 1 to 10 and if the user will type in any value with a fraction part the program cut it off.
But if the user type in a letter the program crash!!!
#include <iostream.h>
#include <limits.h>
main()
{
int n; /* number of values entered */
cout << "How many values? (1..10) -> ";
cin >> n;
cin.ignore(SHRT_MAX, '\n');
/* control number of value entered by the user */
while (n<1||n>10)
{
cout << "\nInvalid input. Try again (1..10) -> ";
cin >> n;
cin.ignore(SHRT_MAX, '\n');
}
}
Thus so far I have got the input will be within the range 1 to 10 and if the user will type in any value with a fraction part the program cut it off.
But if the user type in a letter the program crash!!!
If cin fails to read the type it expects, it will enter an error state and won't accept further input. Try this:
Also, you need to initialize n to something. If the first input fails, n will remain indeterminate, and that could cause a number of problems.
C++ Syntax (Toggle Plain Text)
while (n<1||n>10) { cout << "\nInvalid input. Try again (1..10) -> "; cin.clear(); cin >> n; cin.ignore(SHRT_MAX, '\n'); }
New members chased away this month: 4
![]() |
Other Threads in the C++ Forum
- Previous Thread: Why program works in Dev-C++ and not in VC++ 2005?
- Next Thread: Question
Views: 2253 | Replies: 10
| Thread Tools | Search this Thread |
Tag cloud for C++
6 add api array arrays assignment beginner binary bitmap c++ c/c++ calculator char class classes code compile compiler console conversion convert count data delete desktop directshow dll encryption error file forms fstream function functions game getline givemetehcodez google graph homeworkhelper iamthwee ifstream input int integer java lazy lib linkedlist linux loop looping loops map math matrix memory multidimensional newbie news node number output parameter pointer problem program programming project proxy python random read recursion recursive reference return sort string strings struct studio system template templates text tree unix url variable vector video visual visualstudio win32 windows winsock word wordfrequency wxwidgets







