int main (int argc, constchar * argv[])
{ int labg, quizg, assigng, examg, finalg;
if (argc != 6)
{ cout << "Wrong number of command line arguments" << endl;
return 0;
}
// argv[0] is the program name, so we start from argv[1]
labg = atoi(argv[1]); // convert first parameter to an integer
// etc for the other arguments
// calculate grade ...
}
since labg = atoi(argv[1]);
it only lets the user input lab grades as the first.. i.e.
./a.out -labg 98 -quizg 100 etc...
How do I make it so it doesn't matter which order the user inputs it?
To parse something means to break it apart into individual tokens and then process the individual tokens.
The C runtime has already taken the command line and broken it apart into individual tokens for you. It's given you a list of those tokens starting at argv[1].
Your job is to look at each of those tokens and determine which keyword (e.g. "-labg") it matches. If it matches a keyword, move on to the next token and convert it to a number, then assign it to the appropriate integer (e.g. variable labg).
1 2 3 4 5 6 7
int i = 1; // index to first token
while (i <= argc)
{ if (strcmp(argv[i],"-labg") == 0)
labg = atoi(argv[i+1]);
// repeat for other keywords
i += 2;
}
The above code is just a general outline. It doesn't check that argv[i+1] is a number or even if it exists. It also doesn't deal with the command line being empty or if a keyword doesn't match.