#include #include using namespace std; // // Code to convert a string read in from the command line to an int. // int main(int argc, char** argv) { cout << endl; // This is for reading a value from the command line. // argc is the number of parameters passed to the program // including the command itself. Therefore, // StringToInt 123 will pass argc of 2 to main. if (argc != 2) { cout << "Usage: StringToInt int" << endl; exit(-1); } // Get the 1st parameter which should be the string to convert string myString = argv[1]; int intValue = 0; // Iterate backwards so if the input string is "123" // i will be 2 then 1 then 0 and then the loop will break for (int i=myString.size() - 1;i>=0;i--) { // Get the ith character from the string and convert // from ascii by subtracting ascii '0' from the character. int digit = myString[i] - '0'; // Verify that the digit is between 0 and 9. If not, // an invalid character was entered. if ( (digit < 0) || (digit > 9) ) { cerr << "The character " << myString[i] << " in the input string " << myString << " is not a numerical digit." << endl << endl; exit(-1); } // We first add the 1's digit, then the 10's, then // the 100's, then the 1000's etc etc. int exponent = myString.size() - 1 - i; // Add the digit times the multiplier which is // 10^exponent (10 to the power exponent). intValue += pow(10,exponent) * digit; } cout << intValue << endl << endl; // print out the result. return 0; // Success! }