text to decimal code example
Example 1: english to decimal
#include<iostream>
#include<string>
#include<limits>
inline std::string binary_conv(int,int,std::string);
int main()
{
long int number;
int base {27};
std::cout<<"\nPlease enter a non-negative integer:\t";
std::cin>>number;
while(1)
{
if(std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout<<"\nYou have entered wrong input!"<<std::endl;
std::cout<<"\nPlease enter a non-negative integer:\t";
std::cin>>number;
}
if(!std::cin.fail())
break;
}
std::string binary_number;
binary_number = binary_conv(number,base,binary_number);
std::cout<<binary_number<<std::endl;
return 0 ;
}
std::string binary_conv(int number, int base,std::string binary)
{
std::string zero_one = " abcdefghijklmnopqrstuvwxyz";
if(number==0)
return binary;
binary = zero_one[number%base]+binary;
number/=base;
return binary_conv(number,base,binary);
}
Example 2: english to decimal
#include<iostream>
#include<string>
#include<cmath>
int main()
{
std::cout<<"Please enter a string of small letters and spaces:\t";
std::string str ;
getline(std::cin, str) ;
long int result {0};
long int value {0};
for(int i=0 ; i < str.length(); ++i)
{
switch(str[i]){
case ' ':
value = 0;
break;
case 'A':
case 'a':
value = 1;
break;
case 'B':
case 'b':
value = 2;
break;
case 'C':
case 'c':
value = 3;
break;
case 'D':
case 'd':
value = 4;
break;
case 'E':
case 'e':
value = 5;
break;
case 'F':
case 'f':
value = 6;
break;
case 'G':
case 'g':
value = 7;
break;
case 'H':
case 'h':
value = 8;
break;
case 'I':
case 'i':
value = 9;
break;
case 'J':
case 'j':
value = 10;
break;
case 'K':
case 'k':
value = 11;
break;
case 'L':
case 'l':
value = 12;
break;
case 'M':
case 'm':
value = 13;
break;
case 'N':
case 'n':
value = 14;
break;
case 'O':
case 'o':
value = 15;
case 'P':
case 'p':
value = 16;
break;
case 'Q':
case 'q':
value = 17;
break;
case 'R':
case 'r':
value = 18;
break;
case 'S':
case 's':
value = 19;
break;
case 'T':
case 't':
value = 20;
break;
case 'U':
case 'u':
value = 21;
break;
case 'V':
case 'v':
value = 22;
break;
case 'W':
case 'w':
value = 23;
break;
case 'X':
case 'x':
value = 24;
break;
case 'Y':
case 'y':
value = 25;
break;
case 'Z':
case 'z':
value = 26;
break;
default:
std::cout<<" The input string does not represent a number in base 27 "<<std::endl;
}
int power = (str.length()-1-i);
result += value*(pow(27,power));
}
if(str.length()>= 32)
{
std::cout<<"\nThe input string represents a number that is greater than 2ˆ32"<<std::endl;
}else{
std::cout<<"\n"<<result<<std::endl;
}
return 0 ;
}