in c++ is it possible to have a maximum length of an input, say i am entering a number - is it possible just enforce a rule which says that only a 2 number integer can be entered? i.e 01, 02, 03, 10 20, 30

The simplest way is to do it in a do ... while() loop like this:

// Dev C++
#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    int n;
    
    // keeps looping until a number < 100 is entered
    do 
    {
      cout << "Enter an integer number (< 100): ";
      cin >> n;
    } while (n >= 100);
    
    system("PAUSE");
    return 0;
}

... you have to expand your while() to trap negative numbers too. Maybe add a "user friendly" message too!

well actually you can still write as much as you want to but the input variable will only consist of max 30 signs

Nope. Reduce the value to 2, which is what the OP wanted and test again.
Here is the result of what I get when I enter 30 digits, that's because a 32-bit integer can't hold 30 digits.

123456789012345678901234567890
-858993460
Press any key to continue . . .

and the same with 64-bit integer

1234567890123456789012345678901
-3689348814741910324
Press any key to continue . . .

int main()
{
    __int64 input;
    cin.width(30); // reads max 30 characters/numbers
    cin >> input;
    cout << input << "\n";
}

change the data type to a character array and your method will work

1234567890123456789012345678901
12345678901234567890123456789
Press any key to continue . . .

Nope. Reduce the value to 2, which is what the OP wanted and test again.
Here is the result of what I get when I enter 30 digits, that's because a 32-bit integer can't hold 30 digits.


and the same with 64-bit integer

int main()
{
    __int64 input;
    cin.width(30); // reads max 30 characters/numbers
    cin >> input;
    cout << input << "\n";
}

change the data type to a character array and your method will work

this works for me, and yes I think it only works with char. Sorry to bother you, I thought it worked with int to.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
      char input[30];
      cin.width(30); // reads max 30 characters/numbers
      cin >> input;
      cout << input;
      system("pause>null");
      cin.get();
      cin.get();
      return 0;
      }

I know i shouldn't be using the system("pause"); command but just to make things easier i did

So I guess you will have to user a parser to deal with it,

We can do this :

1) Take the number into a string,
2) Check if it has only digits in it, use isdigit
3) Next check if its 2 digits long, str.size() After that

You could use a basic conversion C-styled or C++ styled... from string to int or const char* to int. And then use the number.

Comments
Good approach :)
This article has been dead for over six months. Start a new discussion instead.