Ah, yes, it is the beginning of the year... so you should be at the beginning of your programming course and not at the end...
Sorry I went over your head.
The basic principles are:
- always read user input as a string, using something like
getline( cin, s );
- test the string to make sure the input is valid
- convert the string to the proper type of thing (integer, float, enum, etc.)
This is not lighthearted stuff. But all robust code that interfaces with the user must have it in some form. In academia people get away without it because the focus is often on other things.
There are as many ways to check input as you can think of. You could, for example, just create a function that tells you if it is good or bad.
getline( cin, s );
if (!isanumber( s )) { cout << "fooey!\n"; return; }
n = converttonumber( s )
Somewhere else you'd have defined the handy little functions isanumber() and converttonumber() to help you. The abstraction and organization of your code is up to you.
T.N.Sharma Be careful:
- Get rid of that
cin>>scores;
! It's pure evil, and getting rid of it is the whole point of this thread. - The argument should be
char scores[]
. - Don't hardcode ASCII values. Use
'0'
and'9'
. - Your function tries to do two things but succeeds with only one.
- if your function determines …