Answer to Question #32636 in C++ for Mike

Question #32636
How can you parse command line arguments and convert them to integers or strings for use elsewhere in the program.
1
Expert's answer
2013-07-02T08:49:49-0400
For getting element from command line you must change your declaration main function.


Main function can actually accept two arguments: one argument is number of command line arguments, and the other argument is a full list of all of the command line arguments.


int main ( int argc, char *argv[] )


The integer, argc is the argument count. It is the number of arguments passed into the program from the command line, including the name of the program.


The array of character pointers is the listing of all the arguments. argv[0] is the name of the program, or an empty string if the name is not available. After that, every element number less than argc is a command line argument.


Default all parameters it's strings. For converting a string to integer you can use function itoa() from stdlib library. On this article you can read about this function:


www.cplusplus.com/reference/cstdlib/itoa/


The program below displays all parameters from command line.



#include <iostream>


using namespace std;


int main(int argc, char *argv[]){
int i;


for(i = 0 ; i < argc ; i++)
cout << argv[i] << endl;


return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS