CPP/CommandLineArguments

From ProgrammingExamples
< CPP
Jump to: navigation, search

CommandLineArgumentsPractical.cpp

#include <iostream>
#include <sstream>
 
// Pass this demo program a float and a string, like this:
// ./MyProgram 2.3 david
int main(int argc, char* argv[])
{
  // Verify arguments
  const unsigned int expectedNumberOfArguments = 2;
  if(argc != expectedNumberOfArguments + 1) // argc is always at least 1 (the program name)
  {
    for(int argumentId = 0; argumentId < argc; ++argumentId)
    {
      std::cerr << "You have not passed the correct number of arguments! (You passed " << argc - 1
                << " but " << expectedNumberOfArguments << " were expected.)" << std::endl;
      return EXIT_FAILURE;
    }
  }
 
  // Parse arguments
 
  // Add all of the arguments to a stringstream
  std::stringstream stringStream;
  for(int argumentId = 1; argumentId < argc; ++argumentId) // start at 1 because this is the first real argument
  {
    std::cout << "argument " << argumentId << ": " << argv[argumentId] << std::endl;
    stringStream << argv[argumentId] << " ";
  }
 
  // Declare the types of the arguments
  float myFloat;
  std::string myString;
 
  // Convert the arguments as their expected types
  stringStream >> myFloat >> myString;
 
  // Output arguments
  std::cout << "myFloat: " << myFloat << std::endl
            << "myString: " << myString << std::endl;
  return 0;
}

CommandLineArgumentsTutorial.cpp

#include <iostream>
#include <string>
#include <sstream>
 
using namespace std;
 
//test with
//24.5 90.3
 
int main(int argc, char *argv[])
{
  int NumArgs = argc - 1;
  cout << "Number of arguments: " << NumArgs << endl;
 
  //argv[0] is the EXE name & is always present.
  string FirstArgument = argv[1];
  string SecondArgument = argv[2];
 
  cout << "FirstArgument: " << FirstArgument << endl;
  cout << "SecondArgument: " << SecondArgument << endl;
 
  stringstream ssArg1, ssArg2;
  ssArg1 << FirstArgument;
  ssArg2 << SecondArgument;
 
  double dArg1, dArg2;
  ssArg1 >> dArg1;
  ssArg2 >> dArg2;
 
  cout << "FirstArgument: " << dArg1 << endl;
  cout << "SecondArgument: " << dArg2 << endl;
 
  std::string test = argv[1];
  cout << "argv[1]: " << argv[1] << endl;
  cout << "argv[1] string: " << test << endl;
 
  return 0;
}