I'm looking for anyone who can explain how the following code works. This is an assignment for a data structures class that I am currently in. I don't want someone to give me code but just an explanation as to how and why it works. The assignment is to parse command line arguments in UNIX. It deals with some topics such as classes, structures etc... that I have not seen for awhile. Any and all help would be greatly appreciated. All of the code has came from the instructor and what he wants the class to do is to use the code he has provided and make a basic calculator, but as stated above, I am completely lost on how his code works. Thank you for your time.
begin file: cmdParser.h
#ifndef PARSER_H
#define PARSER_H
#include <string>
typedefstruct argument
{
std:: string flag;
std:: string value;
}Argument;
class CmdParser
{
public:
CmdParser(int argc, char **argv);
Argument nextArgument();
bool hasNext();
private:
int argc, index;
char **argv;
};
end of file cmdParser.h
begin file cmdParser.cpp
#include "cmdParser.h"
#include <string>
usingnamespace std;
CmdParser::CmdParser(int argc, char **argv)
{
this->argc = argc;
this->argv = argv;
index = 1;
}
Argument CmdParser::nextArgument()
{
Argument result;
if(index >= argc)
return result;
if(argv[index][0] != '-')
{
//handle null flags
result.value = argv[index];
}
else
{
//this is a flag
if(argv[index][1] == '-')
{
//handle the multiple character flag
result.flag = argv[index]] + 2;
}
else
{
//handle single character flag
result.flag = argv[index][1];
//there is a chance the value part is in the same string
if(argv[index][2] != '\0')
result.value = argv[index] + 2;
}
}
}
//advance the index
index++;
if(result.value.empty() && index < argc && argv[index][0] != '-'
{
result.value = argv[index];
index++;
}
return result;
}
bool CmdParser::hasNext()
{
return index < argc;
}
end of file cmdParser.cpp
begin testCmdParser.cpp
#include <iostream>
#include <string>
#include "cmdParser.h"
usingnamespace std;
int main(int argc, char **argv)
{
CmdParser args(argc, argv);
Argument argument;
while(args.hasNext() )
{
argument = args.nextArgument();
if(!argument.flag.empty() )
{
cout << argument.flag << ": ";
}
cout << argument.value << endl;
}
return 0;
}
end of file testCmdParser.cpp
When I began to start coding the assignment, I noticed that I had to
#include "cmdParser.cpp"
From what I have read, this is very bad, but it is the only way that I could get my file to compile.
Just include the header, but make sure you like the results of the source files together (if you are using an IDE, this usually involves adding them to a project of some kind).
As for the actual workings of the class, the most important part is in the nextArgument() method; try reading through that and explaining what is happening at each step and then try to figure out why.