Untitled
unknown
plain_text
a year ago
3.1 kB
19
Indexable
#include<string>
#include<iostream>
#include<cmath>
bool invalidInput();
void ignoreLine();
double userInputDouble();
int checkValidConversion(std::string_view sv);
double convertAToB(int sizeA, double numOf, int sizeB);
bool smallerThanTwo(std::string_view sv);
double userInputDouble()
{
double num{};
while (true)
{
std::cin >> num;
if (invalidInput())
{
std::cout << "invalid input\n";
continue;
}
ignoreLine();
return num;
}
}
void ignoreLine()
{
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
bool invalidInput()
{
if (!std::cin)
{
if (std::cin.eof() && std::cin.peek() != '\n')
{
std::cerr << "ERROR";
std::exit(0);
}
std::cin.clear();
ignoreLine();
return true;
}
return false;
}
int checkValidConversion(std::string_view sv)
{
switch (sv[0])
{
__fallthrough;
case'b':
case'B':
{
if (sv[1] == 'i')
{
std::cout << "bit...\n";
return 1;
}
else if(sv[1]=='y')
{
std::cout << "byte...\n";
return 2;
}
std::cout << "invalid storage type\n";
return 0;
}
__fallthrough;
case'k':
case'K':
{
std::cout << "kilobyte...\n";
return 3;
}
__fallthrough;
case'm':
case'M':
{
std::cout << "megabyte...\n";
return 4;
}
__fallthrough;
case'g':
case'G':
{
std::cout << "gigabyte...\n";
return 5;
}
__fallthrough;
case't':
case'T':
{
std::cout << "terabyte...\n";
return 6;
}
__fallthrough;
case'p':
case'P':
{
std::cout << "petabyte...\n";
return 7;
}
default:
std::cout << "invalid storage type\n";
return 0;
}
}
double convertAToB(int sizeA,double numOf,int sizeB)
{
if (sizeA == 1)
{
numOf /= pow(2, 3);
++sizeA;
}
if (sizeB == 1)
{
numOf *= pow(2, 3);
--sizeA;
}
if (sizeA < sizeB)
{
for (;sizeA < sizeB;++sizeA)
numOf /= pow(10, 3);
}
else if (sizeA > sizeB)
{
for (;sizeA > sizeB;--sizeA)
numOf *= pow(10, 3);
}
return numOf;
}
bool smallerThanTwo(std::string_view sv)
{
if (sv.length() < 2)
return true;
return false;
}
int main()
{
std::string storageSize{};
while (true)//intentional infinite loop
{
std::cout << "Converting A to B, please enter the first 2 characters (e.g. te = terabyte)\nInput A: ";
std::cin >> storageSize;
if (smallerThanTwo(static_cast<std::string_view>(storageSize)))
continue;
int sizeA{ checkValidConversion(static_cast<std::string_view>(storageSize)) };
if (sizeA == 0)
continue;
std::cout << "Insert number of " << storageSize << "s: ";
double numOf{userInputDouble()};
std::cout << "Input B: ";
std::cin >> storageSize;
if (smallerThanTwo(static_cast<std::string_view>(storageSize)))
continue;
int sizeB{ checkValidConversion(static_cast<std::string_view>(storageSize)) };
if (sizeB == 0)
continue;
std::cout << "the number of " << storageSize << "s is: " << convertAToB(sizeA, numOf, sizeB) << '\n';
}
return 0;
}Editor is loading...
Leave a Comment