| | |
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: 2252 | Replies: 10
| Thread Tools | Search this Thread |
Tag cloud for C++
6 api array arrays based beginner binary bmp c++ c/c++ calculator char class classes code compile compiler console conversion convert count data delete deploy dll download dynamic dynamiccharacterarray encryption error file format forms fstream function functions game givemetehcodez graph gui homeworkhelp iamthwee ifstream input int java lib library lines linker list loop looping loops map math matrix memory newbie news number output pointer problem program programming project python random read recursion recursive reference return rpg search simple sort spoonfeeding string strings struct temperature template templates text text-file tree url variable vector video visual visualstudio void win32 windows winsock wordfrequency wxwidgets







