Reading from command prompt - c

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);
}

Related

windows reuse output from previous program as input in other program cmd redirect shell

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.

Using argc and argv in Caesar cipher in C

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 + !.

Segmentation fault in program using command line arguments

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);
}

How can I break a number that I input in the terminal into digits?

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;
}

Reading string character by character in C

So I have a string passed into main function: int main(int argc, char* argv[])
I understand argc (which is 2 in this case), but don't understand how I can read argv[] character by character?
When I print argv[0] shouldn't that print the first character in the array of characters for that string?
Thanks
sample
#include <stdio.h>
int main(int argc, char *argv[]){
int i,j;
for(i=0; i<argc; ++i){
for(j=0; argv[i][j] != '\0'; ++j){
printf("(%c)", argv[i][j]);
}
printf("\n");
}
return 0;
}
One more example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
if(argc != 2)
{
//argv[0] is name of executable
printf("Usage: %s argument\n", argv[0]);
exit(1);
}
else
{
int i;
int length = strlen(argv[1]);
for(i=0;i<length;i++)
{
printf("%c",argv[1][i]);
}
printf("\n");
return 0;
}
}

Resources