#include <iostream>
#include <fstream>
#include <string>
using std::ofstream;
using std::string;
using namespace std;

int main(int argc, char** argp, char** envp)
{
  const char* cstr = "This is a C-style string.";
  cout << cstr << '\n';
  
  string sstr(cstr);                 // How to convert a C-string to C++ string
  cout << sstr << '\n';

  const char* copy = sstr.c_str();   // How to convert a C++ sting to C-string
  cout << copy << '\n';
  
  ofstream fout("arg.txt");    // How to open a file for writing
  
  if (!fout) {                 // How to error check an fstream
    cerr << "File open failed\n";
    return 1;
  }
  
  char** ptr;     // Pointer to a pointer to a C-style string
  char*  str;     // Pointer to a char.
  
                  // Remark: A C-style string is an array of char whose
                  // last element is '\0'.  Most functions that have a 
                  // a pointer to char as an argument assume that it
                  // points to the first element of a C-style string.

  ptr = argp;     // Don't want to change argp so assign to ptr 
  
  for (int i=0; i<argc; i++) {
    str = *ptr++;                  // Derefernce ptr, assign to str, increment
    fout << str << '\n';           // Print str
  }
                                   // Remark: When operator<<'s argument is
                                   // a pointer to char it is assumed to be
                                   // pointer to a C-style string, which is 
                                   // a '\0' terminated array of char.  The
                                   // array is printed, not the pointer value.
  ptr = argp;

  for (int i=0; i<argc; i++) {
    str = *ptr++;                  // Derefernce ptr, assign to str, increment
    while(*str) {                  // C-strings terminated by '\0', i.e., false
      fout << *str++;              // Print one character, increment
    }
    fout << '\n';
  }

  for (int i=0; i<argc; i++) {     // Equivalent, [] dereferences pointers
    fout << argp[i] << '\n';
  }

  for (int i=0; i<argc; i++) {     // Equivalent, [][] dereferences pointers
    int j=0;
    while(argp[i][j]) fout << argp[i][j++];
    fout << '\n';
  }
  
  ofstream envout("env.txt");

  ptr = envp;

  while(*ptr) {                    // Last pointer in envp is null, i.e., 0
    envout << *ptr++ << '\n';
  }

  return 0;
}
