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.
#include <cstdlib>
#include <iostream>
void encryptSwap(int,int,int,int);
usingnamespace std;
int main(){
int num;
//Prompt user to input 4 digit number
cout<<"Enter 4 digit number to be Encrypted"<<endl;
cin>>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!"<<endl;
}
return 0;
}
void encryptSwap(int digit1,int digit2,int digit3,int digit4){
//Replace value
digit1=(digit1+3)%8;
digit2=(digit2+3)%8;
digit3=(digit3+3)%8;
digit4=(digit4+3)%8;
//Swap Values
//Value place holder variables
int x, y;
x=digit2;
y=digit4;
digit2=digit1;
digit1=x;
digit4=digit3;
digit3=y;
//Display encrypted number
cout<<"Encrypted number:"<<endl;
cout<<digit1<<digit2<<digit3<<digit4<<endl;
}
I can't figure out how to keep it only 4 digits with each digit only being 0-7.
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
1 2 3 4
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.
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: