C argc and argv Examples to Parse Command Line Arguments

本文深入探讨了C语言中命令行参数argc和argv的使用,包括如何获取参数数量、参数值以及利用环境变量envp进行程序内部维护。通过示例程序展示如何在C语言中灵活运用这些特性。

http://www.thegeekstuff.com/2013/01/c-argc-argv/


Whenever you execute a program on a terminal, you can pass some arguments that are expected by the program, which can be used during the execution of the program. Here, system provides internal facility to maintain all arguments passed from user while executing program. These arguments are known as “Command line arguments”.

In this tutorial, we will map the understanding of command line arguments with working program to understand it better in crisp and clear way. But before jumping to program, we should know how system provides facility of command line arguments. As we know, Every C program must have main() function and the facility of command line arguments is provided by the main() function itself. When given below declaration is used in program, and then program has facility to use/manipulate command line arguments.

int main (int argc, char *argv[])

Here, argc parameter is the count of total command line arguments passed to executable on execution (including name of executable as first argument). argv parameter is the array of character string of each command line argument passed to executable on execution. If you are new to C programming, you should first understand how C array works.

Given below is the working program using command line argument.

 #include <stdio.h>

 int main (int argc, char *argv[]) {
 int i=0;
 printf("\ncmdline args count=%s", argc);

 /* First argument is executable name only */
 printf("\nexe name=%s", argv[0]);

 for (i=1; i< argc; i++) {
     printf("\narg%d=%s", i, argv[i]);
 }

 printf("\n");
 return 0;
 }

Given below is output when program is executed.

$ ./cmdline_basic test1 test2 test3 test4 1234 56789
cmdline args count=7
 exe name=./cmdline_basic
 arg1=test1
 arg2=test2
 arg3=test3
 arg4=test4
 arg5=1234
 arg6=56789

In above output, we can see total arguments count is internally maintained by “argc” parameter of main() which holds value ‘7’ (in which one argument is executable name and ‘6’ are arguments passed to program).And, all argument values are stored in “argv” parameter of main() which is array of character strings. Here, main () function stores each argument value as character string. We can see, iterating over “argv” array, we can get all passed arguments in the program.

There is one more declaration of main () function that provides added facility to work on environment variables inside program. Like, arguments maintained in argv[] array, main() function has internal facility to maintain all system environment variables into array of character strings which can be taken as an main() function parameter. Given below is the declaration.

int main (int argc, char *argv[], char **envp)

Given below is the working program using command line argument along with environment variables.

#include <stdio.h>

int main (int argc, char *argv[], char **env_var_ptr) {
int i=0;
printf("\ncmdline args count=%d", argc);

/* First argument is executable name only */
printf("\nexe name=%s", argv[0]);

for (i=1; i< argc; i++) {
   printf("\narg%d=%s", i, argv[i]);
 }

i=0;
while (*env_var_ptr != NULL) {
    i++;
    printf ("\nenv var%d=>%s",i, *(env_var_ptr++));
 }

printf("\n");
return 0;
}

Output of above program is given below.

$ ./env test1 test2
cmdline args count=3
 exe name=./env
 arg1=test1
 arg2=test2
 env var1=>SSH_AGENT_PID=1575
 env var2=>KDE_MULTIHEAD=false
 env var3=>SHELL=/bin/bash
 env var4=>TERM=xterm
 env var5=>XDG_SESSION_COOKIE=5edf27907e97deafc70d310550995c84-1352614770.691861-1384749481
 env var6=>GTK2_RC_FILES=/etc/gtk-2.0/gtkrc:/home/sitaram/.gtkrc-2.0:/home/sitaram/.kde/share/config/gtkrc-2.0
 env var7=>KONSOLE_DBUS_SERVICE=:1.76
 env var8=>KONSOLE_PROFILE_NAME=Shell
 env var9=>GS_LIB=/home/sitaram/.fonts
 env var10=>GTK_RC_FILES=/etc/gtk/gtkrc:/home/sitaram/.gtkrc:/home/sitaram/.kde/share/config/gtkrc
 env var11=>WINDOWID=29360154
 env var12=>GNOME_KEYRING_CONTROL=/run/user/sitaram/keyring-2Qx7DW
 env var13=>SHELL_SESSION_ID=f7ac2d9459c74000b6fd9b2df1d48da4
 env var14=>GTK_MODULES=overlay-scrollbar
 env var15=>KDE_FULL_SESSION=true
 env var16=>http_proxy=http://10.0.0.17:8080/
 env var17=>USER=sitaram
 env var18=>LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:
 env var19=>XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session0
 env var20=>XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0
 env var21=>SSH_AUTH_SOCK=/tmp/ssh-kIFY5HttOJxe/agent.1489
 env var22=>ftp_proxy=ftp://10.0.0.17:8080/
 env var23=>SESSION_MANAGER=local/Sitaram:@/tmp/.ICE-unix/1716,unix/Sitaram:/tmp/.ICE-unix/1716
 env var24=>DEFAULTS_PATH=/usr/share/gconf/kde-plasma.default.path
 env var25=>XDG_CONFIG_DIRS=/etc/xdg/xdg-kde-plasma:/etc/xdg
 env var26=>DESKTOP_SESSION=kde-plasma
 env var27=>PATH=/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
 env var28=>PWD=/home/sitaram/test_progs/cmdline
 env var29=>socks_proxy=socks://10.0.0.17:8080/
 env var30=>KONSOLE_DBUS_WINDOW=/Windows/1
 env var31=>KDE_SESSION_UID=1000
 env var32=>LANG=en_IN
 env var33=>GNOME_KEYRING_PID=1478
 env var34=>MANDATORY_PATH=/usr/share/gconf/kde-plasma.mandatory.path
 env var35=>UBUNTU_MENUPROXY=libappmenu.so
 env var36=>KONSOLE_DBUS_SESSION=/Sessions/1
 env var37=>https_proxy=https://10.0.0.17:8080/
 env var38=>GDMSESSION=kde-plasma
 env var39=>SHLVL=1
 env var40=>HOME=/home/sitaram
 env var41=>COLORFGBG=15;0
 env var42=>KDE_SESSION_VERSION=4
 env var43=>LANGUAGE=en_IN:en
 env var44=>XCURSOR_THEME=Oxygen_White
 env var45=>LOGNAME=sitaram
 env var46=>XDG_DATA_DIRS=/usr/share/kde-plasma:/usr/local/share/:/usr/share/
 env var47=>DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-mnJhMvd4jG,guid=435ddd41500fd6c5550ed8d2509f4374
 env var48=>LESSOPEN=| /usr/bin/lesspipe %s
 env var49=>PROFILEHOME=
 env var50=>XDG_RUNTIME_DIR=/run/user/sitaram
 env var51=>DISPLAY=:0
 env var52=>QT_PLUGIN_PATH=/home/sitaram/.kde/lib/kde4/plugins/:/usr/lib/kde4/plugins/
 env var53=>LESSCLOSE=/usr/bin/lesspipe %s %s
 env var54=>XAUTHORITY=/tmp/kde-sitaram/xauth-1000-_0
 env var55=>_=./env
 env var56=>OLDPWD=/home/sitaram/test_progs
$

In above output, we can see all system environment variables can be obtained third parameter of main() function which are traversed in program and displayed in output.

Passing command line arguments to program and manipulate arguments

Given below is program working on command line arguments.

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[]) {
int i=0;
int d;
float f;
long int l;
FILE *file = NULL;
printf("\ncmdline args count=%d", argc);

/* First argument is executable name only */
printf("\nexe name=%s", argv[0]);

for (i=1; i< argc; i++) {
    printf("\narg%d=%s", i, argv[i]);
 }

/* Conversion string into int */
d = atoi(argv[1]);
printf("\nargv[1] in intger=%d",d);

/* Conversion string into float */
f = atof(argv[1]);
printf("\nargv[1] in float=%f",f);

/* Conversion string into long int */
l = strtol(argv[2], NULL, 0);
printf("\nargv[2] in long int=%ld",l);

/*Open file whose path is passed as an argument */
file = fopen( argv[3], "r" );

/* fopen returns NULL pointer on failure */
if ( file == NULL) {
    printf("\nCould not open file");
  }
else {
    printf("\nFile (%s) opened", argv[3]);
    /* Closing file */
    fclose(file);
  }

printf("\n");
return 0;
}

Output of above program is given below.

 $ ./cmdline_strfunc 1234test 12345678 /home/sitaram/test_progs/cmdline/cmdline_strfunc.c
cmdline args count=4
 exe name=./cmdline_strfunc
 arg1=1234test
 arg2=12345678
 arg3=/home/sitaram/test_progs/cmdline/cmdline_strfunc.c
 argv[1] in intger=1234
 argv[1] in float=1234.000000
 argv[2] in long int=12345678
 File (/home/sitaram/test_progs/cmdline/cmdline_strfunc.c) opened

In above output, we can see that command line arguments can be manipulated in program; all arguments are obtained as character string which can be converted into integer, float, long as shown in program. Even any character string if passed as an path of any file that can be used by program to file handling operation oh that file. We can see in above program, (/home/sitaram/test_progs/cmdline/cmdline_strfunc.c ) file path is passed as an command line argument which is used inside program to open the file and close the file.

Getopt() API

If we explore more on command line arguments, we have very powerful API – getopt(). It facilitates programmer to parse command line options. Programmer can give list of mandatory or optional command line options to getopt(). It can determine whether command line option is either valid or invalid as per program expected command line options. There are few getopt() specific internal variables like “optarg, optopt, opterr”

  • Optarg: contains pointer to command line valid option’s argument
  • Optopt: contains command line option if mandatory command line option is missing
  • Opterr: set to non-zero when invalid option is provided or value of mandatory command line option is not given

Given below is basic program to understand parsing of command line options.

 

#include <stdio.h>
#include <unistd.h>

int main (int argc, char *argv[]) {
int opt = 0;
char *in_fname = NULL;
char *out_fname = NULL;

while ((opt = getopt(argc, argv, "i:o:")) != -1) {
    switch(opt) {
    case 'i':
    in_fname = optarg;
    printf("\nInput option value=%s", in_fname);
    break;
    case 'o':
    out_fname = optarg;
    printf("\nOutput option value=%s", out_fname);
    break;
    case '?':
    /* Case when user enters the command as
     * $ ./cmd_exe -i
     */
    if (optopt == 'i') {
    printf("\nMissing mandatory input option");
    /* Case when user enters the command as
     * # ./cmd_exe -o
     */
  } else if (optopt == 'o') {
     printf("\nMissing mandatory output option");
  } else {
     printf("\nInvalid option received");
  }
  break;
 }
 }

printf("\n");
return 0;
 }

Output of above program is given below with few combinations of command line options:

Case1:
$ ./cmdline_getopt -i /tmp/input -o /tmp/output
Input option value=/tmp/input
 Output option value=/tmp/output

Case2:
$ ./cmdline_getopt -i -o /tmp/output
Input option value=-o

Case3:
$ ./cmdline_getopt -i
 ./cmdline_getopt: option requires an argument -- 'i'
Missing mandatory input option

Case4:
$ ./cmdline_getopt -i /tmp/input -o
./cmdline_getopt: option requires an argument -- 'o'
 Input option value=/tmp/input
 Missing mandatory output option

Case5:
$ ./cmdline_getopt -k /tmp/input
 ./cmdline_getopt: invalid option -- 'k'
Invalid option received

In above program, ‘i’ and ‘o’ are taken as mandatory input and output command line options for program using getopt() API.

We would now have basic explanation of each case executed in above program:

  • In Case1, both mandatory command line options with their arguments are provided which are properly handled in first two cases of switch condition of program.
  • In Case2, value of mandatory input option is not given but we can see getopt() is not intelligent enough and considered “-o” as value of ‘I’ command line option. It is not error case for getopt(), but programmer can itself add intelligence to handle such case.
  • In Case3, only command line option is specified without its value and this is mandatory option so in this case getopt() would return ‘?’ and “optopt” variable is set to ‘i’ to confirm mandatory input option’s value is missing.
  • In Case4, mandatory output option’s value is missing.
  • In Case5, invalid command line option is given which is not mandatory or optional command line option. In this case, getopt() returned ‘?’ and optopt is not set since it is unknown character not expected by getopt().

Linux Sysadmin CourseLinux provides several powerful administrative tools and utilities which will help you to manage your systems effectively. If you don’t know what these tools are and how to use them, you could be spending lot of time trying to perform even the basic administrative tasks. The focus of this course is to help you understand system administration tools, which will help you to become an effective Linux system administrator.
Get the Linux Sysadmin Course Now!

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

请查看以下的C++代码的编写要求,请根据代码要求开始编写代码 PURPOSE: This file is a proforma for the EEET2246 Laboratory Code Submission/Test 1. This file defines the assessment task which is worth 10% of course in total - there is no other documentation. At the BASIC FUNCTIONAL REQUIREMENTS level, your goal is to write a program that takes two numbers from the command line and perform and arithmetic operations with them. Additionally your program must be able to take three command line arguments where if the last argument is 'a' an addition is performed, and if 's' then subtraction is performed with the first two arguments. At the FUNCTIONAL REQUIREMENTS level you will be required to extend on the functionality so that the third argument can also be 'm' for multiplication,'d' for division and 'p' for exponential operations, using the first two arguments as the operands. Additionally, at this level basic error detection and handling will be required. The functionality of this lab is relatively simple: + - / * and "raised to the power of" The emphasis in this lab is to achieve the BASIC FUNCTIONALITY REQUIREMENTS first. Once you a basic program functioning then you should attempt the FUNCTIONALITY REQUIREMENTS and develop your code so that it can handle a full range of error detection and handling. ___________________________________________________________________________________________ ___ GENERAL SPECIFICATIONS (mostly common to all three EEET2246 Laboratory Code Submissions): G1. You must rename your file to lab1_1234567.cpp, where 1234567 is your student number. Your filename MUST NEVER EVER contain any spaces. _under_score_is_Fine. You do not need to include the 's' in front of your student number. Canvas will rename your submission by adding a -1, -2 etc. if you resubmit your solution file - This is acceptable. G2. Edit the name/email address string in the main() function to your student number, student email and student name. The format of the student ID line is CSV (Comma Separated Variables) with NO SPACES- student_id,student_email,student_name When the program is run without any operands i.e. simply the name of the executable such as: lab1_1234567.exe the program MUST print student ID string in Comma Separated Values (CSV) format with no spaces. For example the following text should be outputted to the console updated with your student details: "1234567,s1234567@student.rmit.edu.au,FirstName_LastName" G3. All outputs are a single error character or a numerical number, as specified by the FUNCTIONAL REQURMENTS, followed by a linefeed ( endl or \n). G4. DO NOT add more than what is specified to the expected console output. Do NOT add additional information, text or comments to the output console that are not defined within the SPECIFICATIONS/FUNCTIONAL REQURMENTS. G5. DO NOT use 'cin', system("pause"), getchar(), gets(), etc. type functions. Do NOT ask for user input from the keyboard. All input MUST be specified on the command line separated by blank spaces (i.e. use the argv and argc input parameters). G6. DO NOT use the characters: * / \ : ^ ? in your command line arguments as your user input. These are special character and may not be processed as expected, potentially resulting in undefined behaviour of your program. G7. All input MUST be specified on the command line separated by blank spaces (i.e. use the argc and argv[] input parameters). All input and output is case sensitive unless specified. G8. You should use the Integrated Debugging Environment (IDE) to change input arguments during the development process. G9. When your code exits the 'main()' function using the 'return' command, you MUST use zero as the return value. This requirement is for exiting the 'main()' function ONLY. A return value other than zero will indicate that something went wrong to the Autotester and no marks will be awarded. G10. User-defined functions and/or class declarations must be written before the 'main()' function. This is a requirement of the Autotester and failure to do so will result in your code scoring 0% as it will not be compiled correctly by the Autotester. Do NOT put any functions/class definitions after the 'main()' function or modify the comments and blank lines at the end of this file. G11. You MUST run this file as part of a Project - No other *.cpp or *.h files should be added to your solution. G12. You are not permitted to add any other #includes statements to your solution. The only libraries permitted to be used are the ones predefined in this file. G13. Under no circumstances is your code solution to contain any go_to labels - Please note that the '_' has been added to this description so that this file does not flag the Autotester. Code that contains go_to label like syntax will score 0% and will be treated as code that does not compile. G14. Under no circumstances is your code solution to contain any exit_(0) type functions. Please note that the '_' has been added to this description so that this file does not flag the Autotester. Your solution must always exit with a return 0; in main(). Code that contains exit_(0); label like syntax will score 0% and will be treated as code that does not compile. G15. Under no circumstances is your code solution to contain an infinite loop constructs within it. For example usage of while(1), for(int i; ; i++) or anything similar is not permitted. Code that contains an infinite loop will result in a score of 0% for your assessment submission and will be treated as code that does not compile. G16. Under no circumstances is your code solution to contain any S_l_e_e_p() or D_e_l_a_y() like statements - Please note that the '_' has been added to this description so that this file does not flag the Autotester. You can use such statements during your development, however you must remove delays or sleeps from your code prior to submission. This is important, as the Autotester will only give your solution a limited number of seconds to complete (i.e. return 0 in main()). Failure for your code to complete the required operation/s within the allotted execution window will result in the Autotester scoring your code 0 marks for that test. To test if your code will execute in the allotted execution window, check that it completes within a similar time frame as the provided sample binary. G17. Under no circumstances is your code solution to contain any characters from the extended ASCII character set or International typeset characters. Although such characters may compile under a normal system, they will result in your code potentially not compiling under the Autotester environment. Therefore, please ensure that you only use characters: a ... z, A ... Z, 0 ... 9 as your variable and function names or within any literal strings defined within your code. Literal strings can contain '.', '_', '-', and other basic symbols. G18. All output to console should be directed to the standard console (stdout) via cout. Do not use cerr or clog to print to the console. G19. The file you submit must compile without issues as a self contained *.cpp file. Code that does not compile will be graded as a non-negotiable zero mark. G20. All binary numbers within this document have the prefix 0b. This notation is not C++ compliant (depending on the C++ version), however is used to avoid confusion between decimal, hexadecimal and binary number formats within the description and specification provided in this document. For example the number 10 in decimal could be written as 0xA in hexadecimal or 0b1010 in binary. It can equally be written with leading zeroes such as: 0x0A or 0b00001010. For output to the console screen you should only ever display the numerical characters only and omit the 0x or 0b prefixes (unless it is specifically requested). ___________________________________________________________________________________________ ___ BASIC FUNCTIONAL REQUIREMENTS (doing these alone will only get you to approximately 40%): M1. For situation where NO command line arguments are passed to your program: M1.1 Your program must display your correct student details in the format: "3939723,s3939723@student.rmit.edu.au,Yang_Yang" M2. For situation where TWO command line arguments are passed to your program: M2.1 Your program must perform an addition operation, taking the first two arguments as the operands and display only the result to the console with a new line character. Example1: lab1_1234567.exe 10 2 which should calculate 10 + 2 = 12, i.e. the last (and only) line on the console will be: 12 M3. For situations where THREE command line arguments are passed to your program: M3.1 If the third argument is 'a', your program must perform an addition operation, taking the first two arguments as the operands and display only the result to the console with a new line character. M3.2 If the third argument is 's', your program must perform a subtraction operation, taking the first two arguments as the operands and display only the result to the console with a new line character. The second input argument should be subtracted from the first input argument. M4. For situations where less than TWO or more than THREE command line arguments are passed to your program, your program must display the character 'P' to the console with a new line character. M5. For specifications M1 to M4 inclusive: M5.1 Program must return 0 under all situations at exit. M5.2 Program must be able to handle integer arguments. M5.3 Program must be able to handle floating point arguments. M5.4 Program must be able to handle one integer and one floating point argument in any order. Example2: lab1_1234567.exe 10 2 s which should calculate 10 - 2 = 8, i.e. the last (and only) line on the console will be: 8 Example3: lab1_1234567.exe 10 2 which should calculate 10 + 2 = 12, i.e. the last (and only) line on the console will be: 12 Example4: lab1_1234567.exe 10 4 a which should calculate 10 + 4 = 14, i.e. the last (and only) line on the console will be: 14 ___________________________________________________________________________________________ ___ FUNCTIONAL REQUIREMENTS (to get over approximately 50%): E1. For situations where THREE command line arguments (other than 'a' or 's') are passed to your program: E1.1 If the third argument is 'm', your program must perform a multiplication operation, taking the first two arguments as the operands and display only the result to the console with a new line character. E1.2 If the third argument is 'd', your program must perform a division operation, taking the first two arguments as the operands and display only the result to the console with a new line character. E1.3 If the third argument is 'p', your program must perform an exponential operation, taking the first argument as the base operand and the second as the exponent operand. The result must be display to the console with a new line character. Hint: Consider using the pow() function, which has the definition: double pow(double base, double exponent); Example5: lab1_1234567.exe 10 2 d which should calculate 10 / 2 = 5, i.e. the last (and only) line on the console will be: 5 Example6: lab1_1234567.exe 10 2 p which should calculate 10 to power of 2 = 100, i.e. the last (and only) line on the console will be: 100 NOTE1: DO NOT use the character ^ in your command line arguments as your user input. Question: Why don't we use characters such as + - * / ^ ? to determine the operation? Answer: Arguments passed via the command line are processed by the operating system before being passed to your program. During this process, special characters such as + - * / ^ ? are stripped from the input argument stream. Therefore, the input characters: + - * / ^ ? will not be tested for by the autotester. See sections G6 and E7. NOTE2: the pow() and powl() function/s only work correctly for given arguments. Hence, your code should output and error if there is a domain error or undefined subset of values. For example, if the result does not produce a real number you code should handle this as an error. This means that if the base is negative you can't accept and exponent between (but not including) -1 and 1. If you get this then, output a MURPHY's LAW error: "Y" and return 0; NOTE3: zero to the power of zero is also undefined, and should also be treated MURPHY's LAW error. So return "Y" and return 0; In Visual Studio, the 0 to the power of 0 will return 1, so you will need to catch this situation manually, else your code will likely calculate the value as 1. ___ REQUIRED ERROR HANDLING (to get over approximately 70%): The following text lists errors you must detect and a priority of testing. NB: order of testing is important as each test is slight more difficult than the previous test. All outputs should either be numerical or upper-case single characters (followed by a new line). Note that case is important: In C, 'V' is not the same as 'v'. (No quotes are required on the output). E2. Valid operator input: If the third input argument is not a valid operation selection, the output shall be 'V'. Valid operators are ONLY (case sensitive): a addition s subtraction m multiplication d division p exponentiation i.e. to the power of: 2 to the power of 3 = 8 (base exponent p) E3. Basic invalid number detection (Required): Valid numbers are all numbers that the "average Engineering graduate" in Australia would consider valid. Therefore if the first two arguments are not valid decimal numbers, the output shall be 'X'. For example: -130 is valid +100 is valid 1.3 is valid 3 is valid 0.3 is valid .3 is valid ABC123 is not valid 1.3.4 is not valid 123abc is not valid ___ ERROR HANDLING (not marked by the autotester): E4. Intermediate invalid number detection (NOT TESTED BY AUTOTESTER - for your consideration only): If the first two arguments are not valid decimal numbers, the output shall be 'X'. Using comma punctuated numbers and scientific formatted numbers are considered valid. For example: 0000.111 is valid 3,000 is valid - NB: atof() will read this as '3' not as 3000 1,000.9 is valid - NB: atof() will read this as '1' not as 1000.9 1.23e2 is valid 2E2 is valid -3e-0.5 is not valid (an integer must follow after the e or E for floating point number to be valid) 2E2.1 is not valid e-1 is not valid .e3 is not valid E5. Advanced invalid number detection (NOT TESTED BY AUTOTESTER - for your consideration only): If the first two arguments are not valid decimal numbers, the output shall be 'X'. 1.3e-1 is valid 1,00.0 is valid - NB: if the comma is not removed atof() will read this as '1' not as 100 +212+21-2 is not valid - NB: mathematical operation on a number of numbers, not ONE number 5/2 is not valid - NB: mathematical operation on a number of numbers, not ONE number HINT: consider the function atof(), which has the definition: double atof (const char* str); Checking the user input for multiple operators (i.e. + or -) is quite a difficult task. One method may involve writing a 'for' loop which steps through the input argv[] counting the number of operators. This process could also be used to count for decimal points and the like. The multiple operator check should be considered an advanced task and developed once the rest of the code is operational. E6. Input number range checking: All input numbers must be between (and including) +2^16 (65536) or -2^16 (-65536). If the operand is out of range i.e. too small or too big, the output shall be 'R'. LARGE NUMBERS: is 1.2e+999 acceptable input ? what happens if you enter such a number ? try and see. Hint: #INF error - where and when does it come up ? SMALL NUMBERS: is 1.2e-999 acceptable input ? what happens if you enter such a number ? try and see. Test it by writing your own test program. E7. ERROR checks which will NOT be performed are: E7.1 Input characters such as: *.* or / or \ or : or any of these characters: * / ^ ? will not be tested for. E7.2 Range check: some computer systems accept numbers of size 9999e999999 while others flag and infinity error. An infinity error becomes an invalid input Therefore: input for valid numbers will only be tested to the maximum 9.9e99 (Note: 9.9e99 is out of range and your program should output 'R') E8. Division by zero should produce output 'M' E9. Error precedence: If multiple errors occur during a program execution event, your program should only display one error code followed by a newline character and then exit (using a return 0; statement). In general, the precedence of the error reported to the console should be displayed in the order that they appear within this proforma. However to clarify the exact order or precedence for the error characters, the precedence of the displayed error code should occur in this order: 'P' - Incorrect number of input command line arguments (see M4) 'X' - Invalid numerical command line argument 'V' - Invalid third input argument 'R' - operand (command line argument) value out of range 'M' - Division by zero 'Y' - MURPHY'S LAW (undefined error) Therefore if an invalid numerical command line argument and an invalid operation argument are passed to the program, the first error code should be displayed to the console, which in this case would be 'X'. Displaying 'V' or 'Y' would be result in a loss of marks. E10. ANYTHING ELSE THAT CAN GO WRONG (MURPHY'S LAW TEST): If there are any other kinds of errors not covered here, the output shall be 'Y'. Rhetorical question: What for example are the error codes that the Power function returns ? If this happens then the output shall be 'Y'. See section E1.3, NOTE2. ___________________________________________________________________________________________ ___ HINTS: - Use debug mode and a breakpoint at the return statement prior to program finish in main. - What string conversion routines, do you know how to convert strings to number? Look carefully as they will be needed to convert a command line parameter to a number and also check for errors. - ERROR CHECKING: The basic programming rules are simple (as covered in lectures): 1) check that the input is valid. 2) check that the output is valid. 3) if any library function returns an error code USE IT !!! CHECK FOR IT !!! - Most conversion routines do have inbuilt error checking - USE IT !!! That means: test for the error condition and take some action if the error is true. If that means more than 50% of your code is error checking, then that's the way it has to be. ____________________________________________________________________________________________ */ // These are the libraries you are allowed to use to write your solution. Do not add any // additional libraries as the auto-tester will be locked down to the following: #include <iostream> #include <cstdlib> #include <time.h> #include <math.h> #include <errno.h> // leave this one in please, it is required by the Autotester! // Do NOT Add or remove any #include statements to this project!! // All library functions required should be covered by the above // include list. Do not add a *.h file for this project as all your // code should be included in this file. using namespace std; const double MAXRANGE = pow(2.0, 16.0); // 65536 const double MINRANGE = -pow(2.0, 16.0); // All functions to be defined below and above main() - NO exceptions !!! Do NOT // define function below main() as your code will fail to compile in the auto-tester. // WRITE ANY USER DEFINED FUNCTIONS HERE (optional) // all function definitions and prototypes to be defined above this line - NO exceptions !!! int main(int argc, char *argv[]) { // ALL CODE (excluding variable declarations) MUST come after the following 'if' statement if (argc == 1) { // When run with just the program name (no parameters) your code MUST print // student ID string in CSV format. i.e. // "studentNumber,student_email,student_name" // eg: "3939723,s3939723@student.rmit.edu.au,Yang_Yang" // No parameters on command line just the program name // Edit string below: eg: "studentNumber,student_email,student_name" cout << "3939723,s3939723@student.rmit.edu.au,Yang_Yang" << endl; // Failure of your program to do this cout statement correctly will result in a // flat 10% marks penalty! Check this outputs correctly when no arguments are // passed to your program before you submit your file! Do it as your last test! // The convention is to return Zero to signal NO ERRORS (please do not change it). return 0; } //--- START YOUR CODE HERE. // The convention is to return Zero to signal NO ERRORS (please do not change it). // If you change it the AutoTester will assume you have made some major error. return 0; } // No code to be placed below this line - all functions to be defined above main() function. // End of file.
最新发布
08-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值