So, I am trying to use argc and argv in Caesars cipher in order to execute the program with just [./ key ;string] (e.g. ./ 13 Caesar). I have tried in lots of ways, although I must admit I am really lost here. I was thinking I should just use main(void) and ask the input with fgets, but I still have some curiosity in: How could I make it work with “int main(int argc, char *argv[])?”. Any clues you can give me?
Thank you for your help. Here is the code with the current outputs:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
int key;
int result;
char str[60];
int k = 0;
printf("argc =%d\n", argc);
printf("argv =%d\n", argv);
printf("key =%d\n", key);
if (argc != 2)
{
printf("You didn't enter a key.\n");
return 1;
}
else
{
int k = key % 26;
printf("k =%d\n", k);
if (k == 0)
{
printf("Invalid key.\n");
return 1;
}
}
}
Output:
$ ./ceasar 13
argc =2
argv =-13216
key =0
k =0
Invalid key.
Edit: Tentative Answer
int main(int argc, char* argv[])
{
int i;
int key = atoi(argv[1]);
int result;
char str[60];
for (i = 0; i < argc; i++)
{
printf("argv[%d] = %s\n", i, argv[i]);
}
if (argc != 2)
{
printf("You didn't enter a key.\n");
return 1;
}
else
{
if (key == 0)
{
printf("Invalid key.\n");
return 1;
}
}
}
Printing argv with the "%d" specifier is undefined behavior, read printf()'s manual and use "%p".
On the other hand, if you want to print the string you should access the appropriate element with array notation. For example
printf("First Argument: %s\n", argv[1]);
this applies to all arguments, noting that argv[0] is the name of the executable as invoked in the command line.
You should also be careful before accessing argv[1] to check that argc > 2, and always check the current argument + !.
Related
I'm just trying to fetch the input from command prompt and want to convert the input to integer.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int num;
if(atoi(argv)==0)
{
printf("Enter the number : ");
scanf("%d",&num);
}
else
{
num = atoi(argv);
}
}
Above is what I've tried, and I don't know where I've went wrong.
For the below code I'm getting the error as showed in the picture. I want to run it in both the way like getting from the command prompt and if there is no input from command prompt the values must be fetched when the program runs.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int num_of_values,sum = 0;
int i;
float avg;
if(atoi(argv[1])==0)
{
printf("Enter the number of values: ");
scanf("%d",&num_of_values);
int* sum_arr = malloc(num_of_values*sizeof(int));
printf("Enter the values: ");
for(i=0;i<num_of_values;i++)
{
scanf("%d",&sum_arr[i]);
sum+=sum_arr[i];
}
}
else
{
for (i = 2; i<=argc; i++) {
sum+=atoi(argv[i-1]);
}
num_of_values = i-2;
}
avg = sum / num_of_values;
printf("Sum and Average is %d and %f", sum,avg);
}
In if(atoi(argv)==0) you probably want to check how many arguments the user gave at the command line. That's what argc is for.
num = atoi(argv); should be num = atoi(argv[1]);
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int num;
if (argc < 2) { // no argument given on cmdline
printf("Enter the number : ");
if (scanf("%d", &num) != 1) { // check that scanf succeeds
puts("Failed reading a number");
return 1;
}
} else {
num = atoi(argv[1]); // dereferencing the second element
}
printf("num=%d\n", num);
}
Just check for correct number of command-line arguments before calling atoi. If not correct, then throw error and return.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
if (argc != 2)
{
printf("Usage: %s <number>\n", argv[0]);
return -1;
}
int num = atoi(argv[1]);
printf("num = %d\n", num);
}
argv is a pointer. argv[i] is a string. argv[0] will be the program name so argv[1] onwards are the cmd line args.
int main(int argc, char **argv)
{
int num;
if(argc<2) /* user has not provided any cmd line args */
{
printf("Enter the number : ");
scanf("%d",&num);
}
else
{
num = atoi(argv[1]);
}
printf("Number = %d\n",num);
}
I'm trying to check argument count, which should return 1 if there is no argument or more than 2 arguments in command line:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
char *key = argv[1]; //taking the key from CL
int n = strlen(key); //length of CL arg string
if (argc != 2) //checks the amount of CL args
{
printf("Usage: ./substitution key\n");
return 1;
}
for (int i = 0; i < n; i++) //validating the key array
{
if (n != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
else if (!isalpha(key[i]))
{
printf("Key must contain only alphabetic character.\n");
return 1;
}
for (int j = i + 1; j < n; j++)
{
if (key[i] == key[j])
{
printf("Key must not contain repeated characters.\n");
return 1;
}
}
}
}
When i'm running without an argument it throws an error:
runtime error: null pointer passed as argument 1, which is declared to never be null
Segmentation fault (core dumped).
If i'm commenting key validating part, it runs.
I'm new in C programming and googled it a lot.
Please, help me figure out why?
You first access argv[1], which may not exist, then you check argc to see if it exists. This is the wrong order. First check argc, then access argv[1]:
int main(int argc, char *argv[])
{
if (argc != 2) //checks the amount of CL args
{
printf("Usage: ./substitution key\n");
return 1;
}
char *key = argv[1]; //taking the key from CL
int n = strlen(key); //length of CL arg string
// remaining code...
I have an assignment where I'm not allowed to edit the main program, but to free the memory of a copy of argv. So far the only solution I've found is using argc to determine how many blocks need to be freed. However, argc is not an input into the freeing program, but a copy of argv is. Is there anyway to derive argc from **argv?
This should do the trick:
#include <stdio.h>
int main(int argc, char ** argv){
int count = 0;
for(int i = 0; 1; i++)
if(argv[i] == 0) break;
else count++;
printf("Argc: %d\n", count);
}
Or in a compact way (thanks to chqrlie):
#include <stdio.h>
int main(int argc, char **argv) {
int count;
for (count = 0; argv[count] != NULL; count++)
continue;
printf("Argc: %d\n", count);
}
I'm trying to write a program that finds the largest and smallest of 10 numbers.
To use my program, you must use the command line argument -l then numbers to determine largest number, the same for the command -s for smallest numbers.
However, when I don't enter a command at all, and just try to run the program, I receive a segmentation fault. Not sure where I went wrong.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
int i;
int min,max,num;
char *argv1 = argv[1];
char *small = "-s";
char *large = "-l";
min=max=0;
if (0==strcmp(argv1, small))
{
for (i=2; i<argc; i++)
{
num=atoi(argv[i]);
if(i==2)
{
min=num;
}
else
{
if(min>num)min=num;
}
}
printf("The smallest number is %d\n",min);
}
else if (0==strcmp(argv1, large))
{
for (i=2; i<argc; i++)
{
num=atoi(argv[i]);
if(i==2)
{
max=num;
}
else
{
if(max<num)max=num;
}
}
printf("The largest number is %d\n",max);
}
else
{
printf("Invalid option");
}
return 0;
}
Check the number of arguments before accessing to arguments.
int main(int argc, char* argv[])
{
int i;
int min,max,num;
char *argv1 = argv[1];
char *small = "-s";
char *large = "-l";
/* add from here */
if(argc < 2)
{
fprintf(stderr, "Usage: %s command numbers...\n", argc > 0 ? argv[0] : "");
return 1;
}
/* add until here */
min=max=0;
You're setting char *argv1 = argv[1]; without first checking argc to see how many arguments were passed. This will cause a segfault when you later do if (0==strcmp(argv1, small)) because argv1 isn't pointing at a string like you are expecting it to.
To fix it, just check argc before you start comparing argv1 with anything:
if (argc == 1)
{
printf("Error: -s or -l required\n");
exit(1);
}
Ok so what I have to do is input a binary number IN THE TERMINAL, probably using argv[] or something, and then break it into each digit.
What I have is this:
int bits[31];
for(int i=0; i<31 && 1 == fscanf(stdin, "%1d", &bits[i]); ++i);
This works for the scanf, but I would want a SIMPLE way of doing so but with the input being in the terminal
This code accepts a binary number as the program argument. Most of the code is devoted to weeding out any invalid argument.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int len;
long bin;
if (argc < 2) {
printf("Please try again with an argument supplied\n");
return 1;
}
len = strlen(argv[1]);
if (strspn(argv[1], "01") != len) {
printf("The argument is not a binary number\n");
return 1;
}
printf("First bit is %c\n", argv[1][0]);
printf("Last bit is %c\n", argv[1][len-1]);
bin = strtol(argv[1], NULL, 2);
printf("As a long integer variable, the input is %ld\n", bin);
return 0;
}
Without error checking (except against crashing), this reduces to
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int len;
if (argc > 1) {
len = strlen(argv[1]);
printf("First bit is %c\n", argv[1][0]);
printf("Last bit is %c\n", argv[1][len-1]);
printf("As a long integer the input is %ld\n", strtol(argv[1], NULL, 2));
}
return 0;
}