### Help with Limiting Input

I need help with Limiting the user input to only 4 digits and each digit can only be 0-7. It's an encryption program that takes replaces each digit with (sum of the digit + 3)modulus 8. Then swaps the first digit with the second and the third with the fourth. I have a problem with my program allowing numbers with less and more than 4 digits. I can't properly create an if statement.
This is my code.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354`` ``````#include #include void encryptSwap(int,int,int,int); using namespace std; int main(){ int num; //Prompt user to input 4 digit number cout<<"Enter 4 digit number to be Encrypted"<>num; //Variables for each digit int d1,d2,d3,d4; //Grab each individual digit d1=num%10000; d1=d1/1000; d2=num%1000; d2=d2/100; d3=num%100; d3=d3/10; d4=num%10; //Check value if((d1>=0&&d1<=7)&&(d2>=0&&d2<=7)&&(d3>=0&&d3<=7)&&(d4>=0&&d4<=7)){ encryptSwap(d1,d2,d3,d4); }else{ cout<<"Value is Invalid!"<

I can't figure out how to keep it only 4 digits with each digit only being 0-7.
Have you considered getting the input as a char? Then as part of the input validation convert these characters to your int?
Last edited on
Your problem is std::cin grabs all 4 digits then you try to grab the numbers individually that cin has placed in num
 ``1234567`` ``````d1=num%10000; d1=d1/1000; d2=num%1000; d2=d2/100; d3=num%100; d3=d3/10; d4=num%10;``````

What you are actually doing is this:
 ``1234567`` `````` d1=num%10000;//d1 still equals num d1=d1/1000; d2=num%1000;//d2 equals num as well d2=d2/100; d3=num%100;//d3 is num d3=d3/10; d4=num%10;//surprise its num D: ``````

To fix this you could split them up into four separate variables

 ``1234`` ``````cin>>d1; cin>>d2' cin>>d3; cin>>d4; ``````

Unless you overload another operator and make your own cin type function or use bitshift algorithms this function wont work.
Last edited on
So something like this.
 ``12345678910`` `````` char num[4]; int d1,d2,d3,d4; cout<<"Enter 4 digit number"<>num d1=(int)num[0]-48; d2=(int)num[1]-48; d3=(int)num[2]-48; d4=(int)num[3]-48; ``````

I can still accept 5 digits with this though.
ForRealzZzZ wrote:
What you are actually doing is this:
 ``1234567`` `````` d1=num%10000;//d1 still equals num d1=d1/1000; d2=num%1000;//d2 equals num as well d2=d2/100; d3=num%100;//d3 is num d3=d3/10; d4=num%10;//surprise its num D: ``````

I think he had it working the way it was...

 ``12345678`` `````` //let's say num = 9876 d1=num%10000; //d1 = 9876 d1=d1/1000; //d1 = 9 d2=num%1000; //d2 = 876 d2=d2/100; //d2 = 8 d3=num%100; //d3 = 76 d3=d3/10; //d3 = 7 d4=num%10; //d4 = 6 ``````

@Kurisutofaa

Try using `cin.getline(num, 4);`.
http://cplusplus.com/reference/istream/istream/getline/
`char num[3];` ---> 0 1 2 3
`if (d1 > 7 || ...)` ---> get another input
Last edited on
Thanks for the help guys. I got it working properly.
Topic archived. No new replies allowed.