Just posted this question in Unix/Linux Program forum, I was not sure which one I should post in as I am new to the forum. Thanks for your Patience.
Hello, I am almost done with my assignment but I am having trouble figuring out how to fix a test that I am trying to put my program through. I am trying to test is with putting in the command line, what the user should enter for example is
./prog -n [#] [files]...
But the test I am trying to work out is what if the user enters this in the command line
./prog -k
#include <iostream>
#include <fstream>
#include <sstream>
usingnamespace std;
// Preconditions: str is a c-style string
// Postconditions: val has integer represented by the c-style string
// Returns: true if the conversion was successful, false otherwise
bool string_to_integer(char str[], int& converted);
// Postconditions: outputs the usage statement
void usage();
int main(int argc, char* argv[])
{
int linenumber;
ifstream max;
string cheese;
//Below is an if statement that makes sure the user inputs the correct information in the command line
if(argv==0)
{
usage();
}
if (argc==1)
{
usage();
}
//Bellow is where the switch comes into play.
elseif (argc > 2 && string_to_integer(argv[2], linenumber))
{
for (int e=3; e < argc; e++)
{
max.open(argv[e]);
//Bellow is an ifstatement that will output the text if the file does not open correctly
cout << endl << "==> " << argv[e] << " <==" << endl;
if (max.fail())
{
cout << "File did not open correctly." << endl;
continue;
}
//The for-statement below searches each file and reads the lines and displays the lines
for (int g=0; !max.eof() && g<linenumber; g++)
{
std::getline(max, cheese);
cout << cheese << endl;
}
max.close();
}
}
// The else-if statement below would be used if the user only enters in one command from the command line, the else-if statment is when the user enters in greater than 2 commands.
elseif (true)
{
for (int g=1; g < argc; g++)
{
max.open(argv[g]);
cout << endl << "==> " << argv[g] << " <==" << endl;
//Same as above the if-statment below ouputs a message if the file failed to open.
if (max.fail())
{
cout << "File did not open correctly." << endl;
continue;
}
//Like above the for statment reads and outputs the lines being read.
for (int g=0; !max.eof(); g++)
{
getline(max, cheese);
cout << cheese << endl;
}
}
}
//if anything goes weird and the above else-if statments don't work for a command the bellow statment just output the usage statment.
else
{
usage();
}
return 0;
}
bool string_to_integer(char str[], int& val)
{
string std_str( str );
istringstream i( std_str );
i >> val;
return !i.fail();
}
void usage()
{
cout << "usage: comp201_head [-n #] file1 [file2] ..." << endl;
-k is just an invalid value.
im trying to prepare the program incase the user enters an unaccepted command.
-n should be what is entered but I want the usage statement to be output if they enter anything other than that.
like -v or -a
Hope that gives a better idea of what I am trying to do.