This question already has answers here:
How to properly compare command-line arguments?
(4 answers)
Closed 4 years ago.
So I have to write a program that contains two possible options depending on what the user chooses by entering either -i or -w. I'm very new to command line arguments in general and I have no idea how to do this. So far I have:
#include <stdio.h>
int main(int argc, char *argv[])
{
if(argc == -'i') {
puts("Test 1");
}
else if(argc == -'w') {
puts("Test 2");
}
return 0;
}
It doesn't print anything...
Any explanation is greatly appreciated. I'm just trying to understand the logic behind this.
First of all, you are comparing oranges with appels. argc stores the number of
arguments. Second, even if you used argv[1], the comparison would be still
wrong, because it would be comparing pointers, not the contents. Note that in C
a string is a sequence of characters that terminates to '\0'-terminating byte.
A char* variable only points to the start of that sequence. The == operator
checks for equality of values, in case of pointers (and string literals), it
compares whether both pointers point to the same location.
When you want to compare strings, you have to compare the strings themselves,
that means you have to compare the contents where the pointers are pointing to.
For strings you have to use the strcmp function like this:
#include <stdio.h>
int main(int argc, char *argv[])
{
if(argc != 2)
{
fprintf(stderr, "usage: %s option\n", argv[0]);
return 1;
}
if(strcmp(argv[1], "-i") == 0)
puts("Test 1");
else if(strcmp(argv[1], "-w") == 0)
puts("Test 2");
else {
fprintf(stderr, "Invalid option '%s'\n", argv[1]);
return 1;
}
return 0;
}
Note that it is important to check first that you have enough command line
arguments (the first if of my code). If the user didn't pass any argument,
argc will be 1 and argv[1] will point to NULL, which would yield undefined
behaviour if it is passed to strcmp. That's why I only do strcmp when I'm
100% sure that argv[1] is not NULL.
Also if you are coding for a POSIX system (linux, mac, etc), then I recommend using
getopt for parsing of the command line arguments.
You have to check argv[i] where i is the array number of the command line argument being put in, argv[0] would be the file name called upon and after that argv[1] would be the first statement, argv[2] the next and so on
argc means "argument count". meaning the number of arguments
argv is a 2-dimensional array. Strings are 1-dimensional character arrays in C. The second dimension comes from you having multiple String.
So if you want the first String argument, you would access it as follows:
argv[0]
You are also attempting to compare strings, which are more than 1 character long. You should use strcmp to compare strings in C. See How do I properly compare strings?
and if you want to compare equality, you would not use ==, == is for basic data types such as int or char.
argc represents the number of parameters that were passed in at the command line including the program name itself.
In c, a character, e.g., 'i' is an 8-bit number representing the ASCII code of the letter i. So your conditional statement if(argc == -'i') is actually checking whether -105 (105 is the ascii value of the letter i) is the number of arguments that was passed to your program.
To check whether the arguments passed in are "-i" or "-w" you need to perform string comparison, using the c library functions or your own algorithm, and you need to be comparing those strings to argv[i] (where i is the position of the parameter you're checking in the program invocation)
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("The name of the program is %s\n", argv[0]);
if( strcmp(argv[1], "-i") == 0 ) { puts("Test 1"); }
if( strcmp(argv[1], "-w") == 0 ) { puts("Test 2"); }
return 0;
}
Related
I have a c file such that I pass arguments to as such:
./cfile [-size number]
e.g.
./cfile -size 22
Here is an example code for such a file:
int main(int argc, char** argv) {
if (argv[1] != "-size") {
fprintf(stderr, "Wrong format");
return 1;
}
// get_number is some function that returns int value of number if number, NULL otherwise
if (get_number(argv[2]) == NULL) {
fprintf(stderr, "Wrong format");
return 1;
}
return 0;
}
However, when I write
./cfile '-size' '22'
I cannot find a way of making C determine that the apostrophes should not be there.
I want to throw an error due to the apostrophes on each argument, but c seems to treat them as if they are not there.
Is there any way of doing this?
The quotes are interpreted by the shell in order to separate the arguments. They are removed before your program even sees them.
So your program will only see -size for argv[1], not '-size'.
Also, when comparing strings, you need to use strcmp. Using != or == to compare strings is actually comparing pointer values which is not what you want.
This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 1 year ago.
I'm trying the following codes, but got unexpected result.
//the first element in argv[] is a
int main(int argc, char *argv[]) {
char a;
if (*argv == "a")
{
printf("a");
}
}
I got nothing after excution, so that means the condition *argv++ == "a" is false. So why?
In this if statement
if (*argv == "a")
there are compared two pointers. The first one is the pointer to the first character of the string pointed to by the pointer *argv and the second one is the pointer to the first character of the string literal "a".
As these two strings occupy different extents of memory then the comparison of the pointers always evaluates to logical false.
If you want to compare pointed strings then you need to use the standard C string function strcmp. For example
if ( strcmp( *argv, "a" ) == 0 )
If you want to compare first characters of the strings then you should write
if ( **argv == *"a" )
or just use the character 'a' instead of the string literal that is more natural
if ( **argv == 'a' )
Pay attention to that if *argv is not equal to NULL then this pointer points to the string that denotes the running program.
Maybe you actually mean the following if statement
if ( argc > 1 && strcmp( argv[1], "a" ) == 0 )
if you want to check whether the first command line argument is equal tp the string literal "a".
char *argv[] is an array of pointers to char.
// myapp.c - program to print out all command line parameters
#include <stdio.h>
int main (int argc, char *argv[]) {
int i ;
for (i = 0; i < argc; i++) {
printf ("arg %d = %s\n", i + 1, argv[i]) ;
}
return 0 ;
}
If one were to compile this code and run it at the command line like this:
myapp This That another
It would print out
arg 1 = myapp
arg 2 = This
arg 3 = That
arg 4 = another
So, let's say *argv points to 0x0800001000 (in RAM) and "a" is held at address 0x090000000 (in RAM). What you are doing is like saying:
if (0x0800001000 == 0x090000000) {
...
}
which is always going to be false (unless something really weird happens)
I'm not entirely sure what you want to do, but there are two possibilities
You want to compare the first string passed in on the command line to "a"
// do it like this
if (strcmp(argv[1],"a") == 0) {
...
}
You want to compare the first character of the first string passed in on the command line to 'a'
// do it like this
if (argv[1][0] == 'a') {
...
}
We use argv[1] because argv[0] is just the name of the executable
This question already has answers here:
How to check if a string is a number?
(16 answers)
Closed 2 years ago.
I'm currently learning C and I'm messing around with command line inputs from the user.
I understand that argc is the count, i.e. the amount of entered commands, and argv is an array of what was entered.
I know how to check to see if the user entered a value after the called program with argc > 1 etc, and I know that argv takes string type variables which I can convert to real integers using atoi(). However I'm not sure how to implicitly only accepts integers. I've tried using isdigit etc around argv but I usually end up with a segment error. Is there a way around this?
int main(int argc, string argv[])
{
if (argc == 2 && //code to ensure argv[1] is int)
{
//code
}
}
"...not sure how to implicitly only accepts integers."
This is not implicitly done, you have to explicitly test each string for its contents.
Using functions in the string test category, for example isdigit, walk through each of the argv string arguments, i.e from argv[1] through argv[argc - 1] and test the character type to ensure it is a numeric value, from 0 to 9 and -. (Note: other valid numeric char symbols can included, eg: e, x,et.al. but are not in this limited example.)
A simple example:
given command line: prog.exe 23 45 1f4 -57
int main(int argc, char *argv[])
{
for(int i=1;i<argc;i++)
{
if(!test_argv(argv[i]))
{
//notify user of wrong input, and exit
printf("argv[%d] contains non numeric value. Exiting\n", i);
}
}
//continue with program
return 0;
}
bool test_argv(const char *buf)
{
while(*buf)
{
if((!isdigit(*buf)) && (*buf != '-'))
{
return false;
}
buf++;
}
return true;
}
Results in:
I would like to check the arguments in argv[], but it fails to check the second character.
For example,
I can do that:
int main(int argc, char *argv[]){
if (*argv[1] == "A")
printf("Hello: %s\n", argv[1]);
}
However, I can't check argv[1] when I change "A" to "AB" like this:
if (*argv[1] == "AB")
printf("Hello: %s\n", argv[1]);
}
Strings are compared with strcmp() in C, almost never with ==:
if(strcmp(argv[1], "AB") == 0)
printf("the second argument is AB\n");
Note that 0 is returned when the compared strings are equal.
On this line:
if (*argv[1] == "AB")
you're comparing a char to char*. These are different types. Also, even if the first operand was char* you should still not use == to compare strings since it merely compares the pointer values. Use strncmp() instead
if (strncmp("AB", argv[1], 2) == 0)
This condition is true if two first characters of argv[1] are "AB", e.g. if argv[1] is "ABC". If you want to check that argv[1] is exactly "AB" use strcmp() like this
if (strcmp("AB", argv[1]) == 0)
Note that it is fine to use == to compare single characters:
if (argv[1][0] == 'A')
Also, before you assume argv[1] is valid you should check argc to ensure you have actually been given an argument.
*argv[1] is a char. you should not compare it to string (char*). If you want you check if it's A, do if (*argv[1]=='A') If you want to check the whole argument, do it like strcmp(argv[1],"AB")
You should stop comparing pointers and characters, this isn't healthy.
You can do *argv[1]=='A'. And when it comes two two characters, you should use strncmp.
I'm getting a segfault thrown when using invalid input or the -help flag in the command arguments. It is a re-creation of the Unix expand utility, and its supposed to handle errors in a similar fashion.
int main(int argc, char *argv[]){
char help1[]= "-help";
char help2[]= "--help";
int spaces; //number of spaces to replace tabs
if (argc==1){ //if only one argument in stack
//check if asking for help
if ( (strcmp(argv[1], help1)==0) || (strcmp(argv[1], help2)==0) )
printHelp();
else
printError(); //otherwise, print error message
//right number of tokens are provided, need to validate them
} else if (argc>=2){
spaces= atoi(argv[2]); //assign it to spaces
parse_file(spaces); //open the stream and pass on
}
return 0;
}
My printerror method:
void printError(){
fprintf(stderr, "\nInvalid Input.\n");
fprintf(stderr, "The proper format is myexpand -[OPTION] [NUMBER OF SPACES]\n");
exit(1);
}
When I try invalid input or the help flag, I get a segfault. Why is this, since I'm checking if the first flag is help?
If a single command-line parameter is passed to your program, argc == 2, so you need to replace
if (argc==1){ //if only one argument in stack
with
if (argc==2){
Note that in most systems argv[0] is the program name and in this case argc is at least 1. You can think of argc as the number of elements in argv. If you’re testing for argv[1], you’re expecting argv to have at least two elements (argv[0] and argv[1]), hence argc needs to be at least 2.
argv[0] counts too, so if argc==1 argv[1] is NULL
Your help message should be displayed if there are less than 2 parameter given, hence
if (argc<3)
printHelp();
else if(...)
Upon initialization, the arguments to main will meet the following requirements according to this.
argc is greater than zero.
argv[argc] is a null pointer.
argv[0] through to argv[argc-1] are pointers to strings whose meaning will be determined by the program.
argv[0] will be a string containing the program's name or a null string if that is not available. Remaining elements of argv represent the arguments supplied to the program. In cases where there is only support for single-case characters, the contents of these strings will be supplied to the program in lower-case.
As such, you are passing in argv[argc] (which is a null pointer) to strcmp.