Why is my code under giving me back "Not a valid command" when i give the argument print ?
int main(int argc, char *argv[]) {
printf("Argument 2 er %s\n", argv[1]);
if(argv[1] == "print") {
printf("Print kommando kalt");
} else if(argv[1] == "random") {
printf("Random kommando kalt");
} else if(argv[1] == "replace") {
printf("Replace kommando kalt");
} else if(argv[1] == "remove") {
printf("Remove kommando kalt");
} else if(argv[1] == "len") {
printf("øem kommando kalt");
} else {
printf("Ingen gyldig kommando\n");
}
}
You cannot compare C strings using ==. This only does a pointer comparison. You need to use strcmp instead:
if (strcmp(argv[1], "print") == 0) …
Because you cannot compare strings like that in C.
You need to use:
if(strcmp(argv[1], "print") == 0)
printf("Print kommando kalt\n");
And so on.
Also, make sure you don't access argv[1] without making sure it's really there and valid; if your program gets called with no arguments it will be NULL. You can use the value of argc to determine how many arguments you got.
Because argv[1] is a char*: something like 0xDEADBEEF
and "print" behaves as if it is another char*: something like 0xBADF00D
and 0xDEADBEEF != 0xBADF00D
You want to use strcmp() ( http://linux.die.net/man/3/strcmp )
Related
What is the proper way to receive a command line argument from the user and compare it to a single char? For example if the user typed "Y" for yes run some function and "N" for no would run another function.
My main error is "comparison between ptr and integer" & "too few arguments to function call, expected 3 have 1"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void calculate();
void verify();
int main (int argc, char *argv[]) {
if(argc < 2){
printf("Please enter a mode of operation.\n");
return 0;
}
else if(argc > 2){
printf("Too many arguments supplied. Please try again.\n");
return 0;
}
else if(strncmp(argv[1] == 'c') == 0)
calculate();
else if(strncmp(argv[1] == 'v') == 0)
verify();
return 0;
}
void calculate(){
}
void verify(){
}
You're not calling strncmp() correctly. It should be:
strncmp(argv[1], "c", 1)
It takes 3 arguments: two strings and a limit. 'c' is a char, not a string, string literals are put in double quotes.
You can also write simply:
if (argv[1][0] == 'c')
This just checks the first character, so the user can type y or yes and they'll match y. If you want to match the whole argument and require it be just a single character, you should use strcmp() rather than strncmp():
if (strcmp(argv[1], "c") == 0)
This
strncmp(argv[1] == 'c') == 0
just is incorrect syntax. For starters the function strncmp requires three arguments and it deals with strings while in the avove call of the function there is supplied only one argument of type int. because the wrong expression argv[1] == 'c' has type int and is equal to 0.
I can suggest the following solution
else if ( argc > 2 || strlen( argv[1] ) != 1 ){
printf("Too many arguments supplied. Please try again.\n");
return 0;
}
else if ( argv[1][0] == 'c' )
calculateCRC();
else if ( argv[1][0] == 'v' )
verifyCRC();
This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 5 years ago.
I recently wrote a brute force program to turn the octal data from permissions in Unix into the human readable form (e.g. 755 -> rwxr-xr-x) However whenever I run my program called myperm I don't get a result (e.g. ./myperm 755 -> nothing) and I'm not quite sure why can anyone help with this
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[])
{
if (argv[1] == "777")
{
printf("rwxrwxrwx");
}
else if (argv[1] == "755")
{
printf("rwxr-xr-x");
}
else if (argv[1] == "750")
{
printf("rwxr-x---");
}
else if (argv[1] == "700")
{
printf("rwxr-x---");
}
else if (argv[1] == "666")
{
printf("rw-rw-rw");
}
else if (argv[1] == "664")
{
printf("rw-rw-r--");
}
else if (argv[1] == "640")
{
printf("rw-r-----");
}
else if (argv[1] == "600")
{
printf("rw-------");
}
else if (argv[1] == "400")
{
printf("r--------");
}
return (0);
}
Comparing strings in C doesn't work like this, you have to use strcmp
Instead of doing if (argv[1] == "XXX"), you should do if (strcmp(argv[1], "XXX") == 0)
Read on here
argv[1] == "755"
is not how you compare strings in C, you need to use:
strcmp (argv[1], "755") == 0
In any case, this "brute force" method is both totally unnecessary and unreliable (missing possibilities, only nine of the 512 possibilities are handled, even without taking into account setuid and setgid bits and so on).
You would be better off having a function to evaluate one octal digit, such as:
static const char * permXlat (char octal) {
switch (octal) {
case '0' : return "---";
case '1' : return "--x";
case '2' : return "-w-";
case '3' : return "-wx";
case '4' : return "r--";
case '5' : return "r-x";
case '6' : return "rw-";
}
return "rwx";
}
and then processing the argument one character at a time:
printf ("%s%s%s\n",
permXlat (argv[1][0]),
permXlat (argv[1][1]),
permXlat (argv[1][2]));
adding whatever sanity checking you think is necessary (argument list size, character values and so on).
I am having trouble figuring out how to make this code work. What is suppose to is depending on the arguments giving from the command line, it suppose to print out a greeting.
int main (int argc, char *argv[]) {
double testscore;
if (argc == 2) {
printf("Hello, Mr.%s.\n", argv[1]);
}
else if (argc == 3 && argc == testscore) {
testscore = atof(argv[2]);
printf("Hi, Mr.%s, your score is %.1f\n", argv[1], testscore);
}
else {
printf("My name is %s %s.\n", argv[1], argv[2]);
}
}
If someone puts only their last name, then the terminal will print out...
Hello, Mr. last_name
...because they only put in one argument. This works fine.
The part where I am stuck on is when the command line arguments given are == 3. If 3 arguments are given then either the terminal is suppose to print out...
Hi, Mr. last_name, your test score is test_score
...or...
My name is first_name last_name.
If I put in the command line arguments only the last name and test score (Smith 3.4) then it prints out (example using the last name Smith) then it prints out...
My name is Smith 3.4
However, it does work for putting in the first name and last name (John Smith). This gives...
My name is John Smith.
I do not want the answer, I just want what I am doing wrong and hints on how to fix it.
I do not want the answer, I just want what I am doing wrong and hints on how to fix it.
Problem 1: You are using testscore variable before it is being initialized.
Problem 2: You are not performing error handling with atof. I would suggest to use strtod(). You can perform some error handling with it to know that the third argument is a float or not. You can also create your own implementation of atof() which will convert and report error in conversion, if any.
Hint: Try to first check that the number of arguments passed to the c program. After that, try to convert third argument to float using strtod() or your own implementation. If it successfully converts, assign the result of float convrsion to test_score and print last_name and testscore. If not, then consider third argument as last_name and print first_name and last_name.
Your problem is with this line:
else if (argc == 3 && argc == testscore) {
In fact, when argc == 3, then you want to check if argv[2] is a numeric argument.
else if ( (argc==3) && (is_numeric_arg(argv[2])==1)) {
A possible implementation would be:
int is_numeric_arg(char* arg)
{
int isInt = 0;
int isFloat = 0;
int isChar = 0;
char* currChar;
int i = 0;
currChar = arg;
isInt = 1;
while (*currChar != '\0')
{
if(*currChar < '0' || *currChar > '9')
{
if(*currChar == '.' && isInt == 1)
{
isInt = 0;
isFloat = 1;
}
else
{
isInt = 0;
isChar = 1;
}
}
currChar++;
}
if (isChar == 1){ return 0; } // argument is a string
else { return 1; } // argument is a int or float
}
int main (int argc, char *argv[]) {
double testscore;
if (argc == 2) {
printf("Hello, Mr.%s.\n", argv[1]);
}
else if ( (argc==3) && (is_numeric_arg(argv[2])==1)) {
testscore = atof(argv[2]);
printf("Hi, Mr.%s, your score is %.1f\n", argv[1], testscore);
}
else {
printf("My name is %s %s.\n", argv[1], argv[2]);
}
}
I did not test the code and there is probably a better way to check that the argument from the command line is "numeric".
Got it the answer guys. To check it without using another function, it would be
....
else if ( argc==3 && sscanf(argv[2], "%f", testscore)
{
testscore = atof(argv[2]);
printf("Hi, Mr.%s, your score is %.1f\n", argv[1], testscore);
}
...
I am getting input as argv, argc and I want to return TRUE of FALSE according to the input. My code is :
int is_valid_regexp(const char* regexp);
int main(int argc, char *argv[])
{
if (!is_valid_regexp(argv[1])){
fprintf(stderr, "wrong regular expression format:%s", argv[1]);
return(EXIT_FAILURE):
}
return (EXIT_SUCCESS);
}
int is_valid_regexp(const char* regexp)
{
do{
if(*regexp == '\\')
return FALSE;
}while (regexp++ != '\0');
return TRUE;
}
The program executes and then stops working. I think something is wrong with if(*regexp == '\\') return FALSE - the program works well if I exclude that part. Does it have something to do with pointer problem?
}while (regexp++ != '\0');
Here, regexp is a POINTER, which is equal to address of area of memory. regexp++ just shift right on one position this pointer. As type of pointer is size_t (unsigned __int32) you go outside your string.
Use
`}while (*regexp++ != '\0');`
to solve your problem.
This question already has answers here:
How to compare strings in an "if" statement? [duplicate]
(5 answers)
Closed 8 years ago.
I am running this program with with ./crack 50yoN9fp966dU
50yoN9fp966dU is crimson encrypted. which is on the word list. My program is as follow:
#define _XOPEN_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if(argc > 2)
{
printf("Invalid Argument \n");
return 1;
}
else
{
FILE *fp1;
fp1 = fopen("/usr/share/dict/words", "r");
char line[9];
while (fgets(line, 9, fp1) != NULL)
{
char *EncryptLine1;
char *EncryptLine2;
printf("%s", line);
EncryptLine1 = crypt(line, "50");
if(argv[1] == EncryptLine1)
{
printf("%s \n", line);
}
EncryptLine2 = crypt(line, "HA");
if(argv[1] == EncryptLine2)
{
printf("%s \n", EncryptLine2);
}
}
}
}
If I add a printf("%s", EncryptLine1), I see the argv[1], i.e 50yoN9fp966dU, but the loop continue and does not print the answer.
You are doing pointer comparison instead of contents (pointed data) comparison.
Change this:
if (argv[1] == EncryptLine1)
To this:
if (strcmp(argv[1],EncryptLine1) == 0)
And this:
if (argv[1] == EncryptLine2)
To this:
if (strcmp(argv[1],EncryptLine2) == 0)
You have some problems in your code:
You blithely assume argc will never be smaller than 2. Check for unequal 2 instead of bigger two in your first condition.
Anyway, if you return out of an if-block, using else and doing deeper nesting is really superfluous.
Strings cannot be compared with ==, use strcmp.:
if( ! strcmp(argv[1], EncryptLine1))
You need to add a break to break out of the loop or a return to leave the function in your conditional block after printing success, if you want to end the loop there.
if( ! strcmp(argv[1], EncryptLine1)) {
printf("%s \n", line);
break;
}
BTW: Why don't you reuse EncryptLine1 (not that you need any temporary at all there)?
argv[1], EncryptLine1 and EncryptLine2 are all char*s. operator== on two char*s simply checks to see if they are pointing to the same memory location. What you want is to compare the contents of the strings they represent. So, the ifs should look like this:
if(!strcmp(argv[1], EncryptLine1))