C++ program that uses command line arguments Write a program that will implement
ID: 3844367 • Letter: C
Question
C++ program that uses command line arguments
Write a program that will implement command line options.
Example will follow.
The first option will obviously be the program.
The second option (if present, will be something like “-d”, or “-s”, etc).
The third option will be a keyword that will need to be used further in the program.
Fourth option will be an input file name that the user inputs.
Fifth option will be an output file for the text to go to.
Example:
This is an example with the second option present:
./test -d YOLO input.txt output.txt
This is an example without the second option present:
./test YOLO input.txt output.txt
Explanation / Answer
#include<iostream>
#include<cstring>
#define DEFAULT_OPTION 's'
using namespace std;
void fun(char option, char* keyword, char* inFile, char* outFile) {
cout << "Option selected is: " << option <<endl;
cout << "Keyword selected is: " << keyword <<endl;
cout << "Input file selected is: " << inFile <<endl;
cout << "Output file selected is: " << outFile <<endl;
}
int main (int argc, char *argv[])
{
int index = 1;
char option = DEFAULT_OPTION;
char keyword[20];
char inFile[50];
char outFile[50];
switch(argc) {
case 5: // 5 params are present
if (argv[index][0] == '-' && strlen(argv[index]) == 2)
option = argv[index][1];
index++;
case 4: //if we have missing 2nd param
strcpy(keyword,argv[index++]);
strcpy(inFile,argv[index++]);
strcpy(inFile,argv[index++]);
break;
default:
cout << "Format not correct" << endl;
return 1;
}
fun(option,keyword,inFile,outFile);
}
This answer should work well. All you need to do is implemnt the fun function the way you want to meet your requirments
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.