Error for character entries...

So... I found out that for this problem I HAVE to use an unsigned short for the acct #, which is the first variable. I am brand new to arrays, so I am in uncharted territory. My code still worked (acct[7]) even thought it wasnt a char. However, the only way I could display the # at the end was with that awkward typing out of every place holder in the array. Is there a better way of doing that?

Also, now if someone enters a character by accident, it is read as '0'. Is there a way I can make a separate error for character entries? I am trying not to include the limit or cstring libraries because we havent been taught those yet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  unsigned short acct[7], acctBal, check, deposit;
                cout<<"Enter your 6 Digit Account #: "<<endl;
                cout<<"Please key in one digit at a time"<<endl;
                for (int i=1;i<7;i++) {
                    //Prompts user for which digit it wants.
                    cout<<"Enter Digit "<<i<<" Then Press Return:"<<endl;
                    cin>>acct[i];
                    //Error entry net; ensure entry is a Digit, not a letter.
                        if(acct[i]<0||acct[i]>9){
                            cout<<"Error"<<endl;
                            i--;
                        }
                }
                cout<<acct[1]<<acct[2]<<acct[3]<<acct[4]<<acct[5]<<acct[6]<<endl;
Hi,

The idiom of a for loop is:
1
2
3
4
5
6
const unsigned int SIZE = 6; // do this to avoid magic numbers like 7 in your code

unsigned short acct[SIZE];
for (int i = 0; i  < SIZE ; i++) {
    // Your code
}


Arrays start at 0, so acct[7] is out of bounds for your declaration of acct[7].

To print out an array, use a for loop again, with a std::cout inside.

Avoid declaring several variables on the same line, do 1 per line and initialise them to something. Not initialising variables, or rather the use of them is one of the biggest source of errors.

Line 9 doesn't do what you think: The ascii codes go from 0 to 127 or 255; the first 32 aren't printable - have a look at the ascii table to see which ones are numerals.

std::cout has error states like bad and fail etc - have a look at the documentation at the top left of this page.

Hope all goes well.

I am not sure what you mean by ASCII codes in line 9. Line 9 is making sure that the unsigned short value is within 0 and 9; so, ensuring that it is a single digit. So if the user enters 44, it produces an error.

This code does work, its just if you enter a character, it takes it as a 0.

Or am I the one misunderstanding?
As TheIdeasMan said loop should start at 0 and go up to SIZE-1, so use the loop he posted.
Also, you are expecting short as input if you enter something other than 0-9 digits then that will be taken as 0
Topic archived. No new replies allowed.