0

I want to make a check of typed length in this array. Here must be typed eight numbers. Here is my code:

#include <iostream.h>
#include <iomanip.h>

void main () 
{
    int n, i;
    cout << "1. Vyvedi fakulteten nomer" << endl;
    cin >> n;
    switch(n) {
    case 1:
        int F[30];
        for (i=1; i<=30; i++) {
            cout << i << ". Fak. nomer: ";
            cin >> F[i];
        }
    }
}
Nikos C.
  • 50,738
  • 9
  • 71
  • 96
  • The question is if i type "12345678" then the cycle will continue with 2... if i type "123456" the program must tell me that i need 8 numbers to contunie ... – Nikola Obretenov Nov 11 '12 at 16:31

2 Answers2

0

If you need 8 digits, then you know that the input must be between 10000000 and 99999999. So simply check for that:

cin >> n;
if (n < 10000000 or n > 99999999) {
    // Error: need 8 digits.
}

That works for positive numbers. If you also need to handle negative numbers, adjust the condition accordingly.

If you also need to extract each digit from the number, then this has been answered here many times now. For example: How to get the Nth digit of an integer with bit-wise operations?

Community
  • 1
  • 1
Nikos C.
  • 50,738
  • 9
  • 71
  • 96
  • I need to make a check if the input length in console is <8 && >8 to show a message "You need 8 numbers to continue" ... – Nikola Obretenov Nov 11 '12 at 16:46
  • `cin >>` will read one number at a time. When you reach 8, just stop. If the user entered less than 8, `cin >>` will continue to expect input, it doesn't matter if the user presses Enter. – Nikos C. Nov 11 '12 at 16:50
  • So i need to put not int F[30]. I need to put char[30] ? char will help me to count different symbols ? help me with excatly code. – Nikola Obretenov Nov 11 '12 at 16:54
  • Nope, you still use `int`. Unless you don't mean 8 numbers, but 8 digits. Do you want 8 numbers, or 8 digits? – Nikos C. Nov 11 '12 at 16:57
  • upsss .... my bad... i need 8 digits... if digits<8 && digits>8 then program show msg to type 8 digits to continue – Nikola Obretenov Nov 11 '12 at 16:58
0

The usual routine for input correctness checking uses a do while loop

 int input;
 do
 {
      std::cin >> input;
 }
 while(input < 10000000 || input > 99999999);

This way, the program will wait for valid input until it's provided. No need for arrays here. If the program need to process VERY large numbers that don't fit in any integer type, then you can read it as a string

 std::string input;
 do
 {
      std::cin >> input;
 }while(input.length() != my_desired_length);
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434