Skip to content

Instantly share code, notes, and snippets.

@bdeleasa
Last active September 23, 2018 22:37
Show Gist options
  • Save bdeleasa/758b561d253c2d2e5556e7b21e3fd82f to your computer and use it in GitHub Desktop.
Save bdeleasa/758b561d253c2d2e5556e7b21e3fd82f to your computer and use it in GitHub Desktop.
A c++ app for converting CM to inches. Helping a friend out by getting it partially working for his homework. :)
#include <iostream>
using namespace std;
int main( int argc, char *argv[] ) {
string firstArg = "";
char * secondArg;
// Warning if no arguments are found
if ( argc == 0 ) {
cout << "Warning! You didn't enter any arguments.\n";
return 0; // Get out
}
// No need for a for loop since you know you're only accepting two arguments.
// Just check if we have the first argument.
if ( argv[1] != NULL ) {
string firstArg = argv[1];
// I would give the warning about the valid arguments here before you do anything else
if ( firstArg != "help" && firstArg != "i" && firstArg != "c") {
cout << "Warning! You didn't use a valid argument. Please use 'help', 'i', or 'c' as the first argument.\n";
return 0; // Get out
}
// Show the help message and then exit because the rest of the program isn't necessary
// if the user entered this.
if ( firstArg == "help" ) {
cout << "Usage: Converting in to cm or cm to in\n";
cout << "i for in to cm conversion\n";
cout << "c for cm to in conversion\n";
cout << "Example: `i 10` or `c 20`\n";
return 0;
}
}
// Now check for the second argument
if ( argv[2] != NULL ) {
secondArg = argv[2];
// @todo Now you can modify everything below and remove the user input here. We no longer need it since we're getting the unit and value directly from the command line (`i 10`). Use second argument (argv[2]) to calculate the value below instead. I left some pseudo code below to outline what you may do:
// If the first argument was i, use the second argument and calculate inches to centemeters
// If the first argument was c, use the second argument and calculate centimeters to inches
// Return the value
const double cm2inch = 2.54;
int val;
char unit;
cout << "Please type in a unit and its value.\n";
cout << "Type in 'help' for man page.\n";
while (cin >> val >> unit) {
if (unit == 'i')
cout << val << "in == " << val * cm2inch << "cm\n";
else if (unit == 'c')
cout << val << "cm == " << val / cm2inch << "in\n";
else
return 0;
}
}
else {
// Warn them if they didn't enter a second argument
cout << "Warning! You didn't enter a numeric value to convert.\n";
return 0; // Get out
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment