This example demonstrates converting appropriately formed string objects and C-strings into numeric values. The example also provides another demonstration of using command-line arguments. We must recognize that argv is an array of character pointers, meaning that all command line arguments, even those the program processes as numbers, are C-strings.
We return to the pyramid.cpp program written in chapter 3 to provide the context for the current demonstration. The "real" problem-solving occurs in the earlier example, which you should review. In the previous version, we hard-coded the pyramid's height as a symbolic constant. In this version, we have the user enter the height of the pyramid on the command line. All command-line data enters the program as a C-string, so the first version converts the height entered on the command line from a C-string to an integer. The second version checks the command line for data input. If the user enters the height on the command, the program uses it; otherwise, it prompts the user to enter it through the console. The third and final version introduces an intermediate string object into the conversion process.
#include <iostream> using namespace std; int main(int argc, char* argv[]) // (a) { int height = atoi(argv[1]); // (b) for (int level = 0; level < height; level++) { for (int spaces = 0; spaces < height - level - 1; spaces++) cout << ' '; for (int xes = 0; xes < 2 * level + 1; xes++) cout << 'X'; cout << endl; } return 0; }
#include <iostream> using namespace std; int main(int argc, char* argv[]) { int height;if (argc == 2) height = atoi(argv[1]); else { cout << "Please enter the pyramid height: "; cin >> height; }for (int level = 0; level < height; level++) { for (int spaces = 0; spaces < height - level - 1; spaces++) cout << ' '; for (int xes = 0; xes < 2 * level + 1; xes++) cout << 'X'; cout << endl; } return 0; }
#include <iostream> #include <string> using namespace std; int main(int argc, char* argv[]) { int height; if (argc == 2) { string st_height = argv[1]; // (a) height = stoi(st_height); // (b) } else { cout << "Please enter the pyramid height: "; cin >> height; } for (int level = 0; level < height; level++) { for (int spaces = 0; spaces < height - level - 1; spaces++) cout << ' '; for (int xes = 0; xes < 2 * level + 1; xes++) cout << 'X'; cout << endl; } return 0; }