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);
}
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 wanna do this:
Progam1 | Program2
I wanna use the output of the first program as input(stdin) for the program2 to do some calculations.
for now this is what i have in program 2
int main(int argc, char *argv[]) {
char userInput[100];
int num[100];
FILE *cmdLn = stdin;
if (argc > 2) {
fprintf(stderr, "Usage: %s [<file>]\n", argv[0]);
exit(EXIT_FAILURE);
}
if (argc == 2) {
cmdLn = fopen(argv[1], "r");
if (!cmdLn) {
perror(argv[0]);
exit(EXIT_FAILURE);
}
}
int numInput[100];
for (int i = 0; i < 100; i++) {
fscanf(cmdLn, "%d", &numInput[i]);
printf("%d\n", 2*numInput[i]);
}
if (cmdLn != stdin) {
fclose(cmdLn);
}
exit(EXIT_SUCCESS);
}
program 1 just creates several numbers per row. I want to use those numbers in program 2 to double them and print the result.
What am I missing here?
I am reading from with fgets from *file which is getting input from stdin
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char userInput[100];
int numInput[100];
FILE *file = stdin;
if (argc > 2) {
fprintf(stderr, "Usage: %s [<file>]\n", argv[0]);
exit(EXIT_FAILURE);
}
if (argc == 2) {
file = fopen(argv[1], "r");
if (!file) {
perror(argv[0]);
exit(EXIT_FAILURE);
}
}
int num[100];
while (fgets(userInput, sizeof(userInput), file))
{
num[i] = atoi(userInput);
printf("%d\n", 2*num[i]);
i++;
}
if (file != stdin) {
fclose(file);
}
exit(EXIT_SUCCESS);
}
the shell redirection works, but not exactly how I want.
Program 1 gives me 10random int numbers.
when I get 10 different numbers from program 1 and pipe its output to program 2 I get new 10 random values and not the output of program 1 before.
program 2 should calculate those(e.g. multiply by 2).
Maybe the problem lies in program 1:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXNUM 1000
int main(int argc,char *argv[]) {
char *userInput[10];
time_t t;
int num = atoi(argv[1]);
srand(time(NULL));
for (int i = 0; i <= num; i++) {
printf("%d\n", rand() % MAXNUM);
}
return 0;
}
the problem is that it generates new random numbers. But I want to use the output of this program and multiply it with 2 with program 2
I think I fixed it! Yeehawww!
It was the srand() causing this problem. Uncommenting that solved it.
#include <stdio.h>
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: one file only", argv[0]);
return (1);
} else {
for(int i = 0; i < argc; i++) {
putchar(argv[i]);
}
}
}
Say I want to print the input it takes in, for instance
$ gcc -Wall fileabove.c
$ ./a.out abcdefghijlmn
abcdefghijlmn
Basically just prints out whatever text I put into it.
putchar(argv[i]);
is incorrect, because putchar expects a single character (type char), you are passing a pointer (char*). It should be
puts(argv[i]);
So the correct code:
#include <stdio.h>
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: one file only\n", argv[0]);
return 1;
}
// no need for the else
// you exit program anyway if argc != 2
// makes code more readable
puts(argv[1]);
return 0;
}
If you want to print character by character:
#include <stdio.h>
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: one file only\n", argv[0]);
return (1);
}
for(size_t i = 0; argv[1][i] != '\0'; ++i)
putchar(argv[1][i]);
putchar('\n');
return 0;
}
edit changed puts("") to putchar('\n') and removed strlen as Jonathan Leffler mentioned in the comments.
The argument array is always in the format of first index being the called program name and the subsequent index values being the parameters in order. Because you only want one argument to process, I have simplified your code as follows:
#include <stdio.h>
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "%s usage: one file only\n", argv[0]);
return 1;
} else {
printf("%s\n",argv[1]); //print only parameter and new line
}
return 0;
}
When the user doesn't specify one parameter, then the error pops up including the program name. When the parameter is specified, it is stored in the second index of the array (index 1) and in my code, I simply printed it out using printf.
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 + !.