using if statements with command line parameters in c - c

I am having trouble with getting my if statements to work with parameters from the command line. I get an error saying, 'comparison between pointer and integer ('char *' and 'int')' every time. Any help will be greatly appreciated. Here is the description for what I have to do:
This program will read a parameter from the command line and translate it to the name of the corresponding month. I.e. if you run the program with the following parameter:
It will print the following message:
The month is 'April'.
#include <stdio.h>
int main(int argc, char *argv[]) {
if(argv[1] == 1){
printf("You entered the number 1.");
} else {
printf("You entered a different number.");
}
return 0;
}

The parameters passed on the command line are strings, so you need to use strcmp to compare them.
int main(int argc, char *argv[]) {
if(argc > 1 && (strcmp(argv[1],"1") == 0)){
printf("You entered the number 1.");
} else {
printf("You entered a different number.");
}
return 0;
}

Compiler is right - you are comparing char * and int.
You have to either convert argv[1] to int (e.g. with strol()) or convert 1 to char * (by adding quotes - "1") and then compare with strcmp() instead of ==.
And checking number of arguments in argc is also something you should do, when working with arguments. (thanks #Ingo Leonhardt)

Argv returns pointer to array of chars, so your programm must looks like:
#include <stdio.h>
int main(int argc, char *argv[]) {
if(argv[1][0] == '1'){
printf("You entered the number 1.");
} else {
printf("You entered a different number.");
}
return 0;
}
Or you can use atoi (man 2 atoi) function to convert ascii array to int like this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if(atoi(argv[1]) == 1){
printf("You entered the number 1.");
} else {
printf("You entered a different number.");
}
return 0;
}

If you want to use your command line parameter like a integer, you must modify the type with atoi
#include <stdio.h>
int main(int argc, char *argv[]) {
if(atoi(argv[1]) == 1){
printf("You entered the number 1.");
} else {
printf("You entered a different number.");
}
return 0;
}

Related

Command line parameter in C

I get segmentation error when I give my program parameter '2' or '3'. It should print That's number two/three. What's the error here?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc > 1) {
if (*argv[2] == '2') {
printf("That's number two!");
}
else if (*argv[2] == '3') {
printf("That's number 3!");
}
else
printf("Error.\n");
}
else
printf("No input given.\n");
return 0;
}
When I run the program, I type ./Test 2 or 3. I can't find a error, and gcc does not give errors / warnings either.
Thanks.
if (*argv[1] == '2') {
printf("That's number two!");
}
else if (*argv[1] == '3') {
printf("That's number 3!");
}
Index begins with 0.
argv[0] is the name of the program and argv[1] is the first command line parameter.
argv is an array:
argv[0] // the name of the executable
argv[1] // the first argument
argv[...]
When you do:
if (*argv[2] == '2')
and you were called with ./Test 2, there is only a single argument, so argv[2] is an out-of-bounds access.
For more information, see main function.

C getting input from CMD

How do you get input using prompt? I tried compiling the code bellow into "a.exe" and executing it from CMD like "gcc a.exe 5", but it doesn't output the number like it was supposed to.
#include <stdio.h>
int main(int a)
{
printf("%d\n", a);
return 1;
}
Have I done anything wrong when installing the compiler or am I trying to run it wrong?
Your main() parameters are wrong, you should do it this way:
int main(int argc, char **argv) {
if(argc > 2) {
printf("%s\n", argv[2]);
}
else {
printf("No arguments\n");
}
}
Note that int argc represents the number of parameters and char **argv is an array containing all the parameters, as strings, including "gcc", "a.exe", etc.
In your case, if you run your program this way: gcc a.exe 5, your parameters would be: argc = 3, argv = ["gcc", "a.exe", "5"]
To get input using the prompt, the easiest way would simply be to use a scanf statement. scanf basically waits for, and scans user input, which can then be stored as a variable. For example, a code that would take input for "Give me a number." and then spits back the result would be:
#include <stdio.h>
int main()
{
int num; //Initializes variable
printf("Please give me a number.\n"); //Asks for input
scanf("%d", &num); //scanf is the function, %d reserves the space, and the &*variable* sets the input equal to the variable.
getchar(); //Waits for user to input.
printf("Your number was %d.\n", num); //Spits it back out.
return 0;
}
The output would be:
[PROGRAM BEGINS]
Please give me a number.
>>>5
Your number was 5.
[PROGRAM ENDS]
#include <stdio.h>
int main(int argc, char *argv[])
{
if(argc == 2)
printf("%d\n", atoi(argv[1]));
return 0;
}

Anagram problems

I'm new to this forum and would like to seek help. I'm trying to modify an anagram program based on code from http://www.sanfoundry.com/c-program-...ings-anagrams/.
This time, however, I have used array pointers to obtain input from the user. I have also created a function "check_input" to ensure that the input consists of ONLY characters and excludes symbols(!, #, $). However, when I ran the program, it still accepts those symbols and does not break like I wanted it to. Please help.
Plus, I intend to make the program treat upper-case letters the same way as lower-case letters. Can this be achieved by using the "stricmp" function? If so, where should I place that function? Alternative methods are also appreciated.
Update: Sorry. I've added the check_input code at the bottom.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int test_anagram(char *ptrArray1, char *ptrArray2);
int check_input(char array1[], char array2[]);
int main()
{
char array1[100], array2[100];
char *pArray1, *pArray2;
int flag;
pArray1 = array1;
pArray2 = array2;
printf("Enter the first word: \n");
gets(pArray1);
printf("Enter the second word: \n");
gets(pArray2);
check_input(pArray1, pArray2);
flag = test_anagram(pArray1, pArray2);
if(flag == 1){
printf("\"%s\" and \"%s\" are anagrams.\n", pArray1, pArray2);
}else{
printf("\"%s\" and \"%s\" are not anagrams.\n", pArray1, pArray2);
}
return 0;
}
int test_anagram(char array1[], char array2[])
{
int num1[26] = {0}, num2[26] = {0}, i = 0;
while(array1[i] != '\0')
{
num1[array1[i] - 'a']++;
i++;
}
i = 0;
while(array2[i] != '\0')
{
num2[array2[i] - 'a']++;
i++;
}
for(i=0;i<26;i++)
{
if(num1[i] != num2[i]){
return 0;
}
return 1;
}
}
int check_input(char array1[], char array2[])
{
while(isalpha((int)array1) != 1){
break;
}
while(isalpha((int)array2) != 1){
break;
}
}
You haven't (yet) posted the full code of the check_input() function but one advice would be to validate the input when the user inputs every character.
You can do this using f.e. the getchar() function and checking if the inputted character is a letter, as well as converting it to the lowercase (or uppercase if you will).
You can do lowercase convertion like this:
#include <ctype.h>
// ...
tolower('A');

validate the number of inputs in c

I'm writing a code which needs to accept command line input. input validation is part of the marking criteria so I'm writing a piece of code to check that exactly one number is entered so I can put it in the main code later (adding an else case for invalid input to bug the user)
#include<stdio.h>
int main(int argc, char* argv[])
{
double a;
a = 75;
if(argc == 2);
{
sscanf(argv[1], "%lf", &a);
printf("%lf \n", a);
}
printf("%d% \n", argc);
return(0);
}
the program prints a when at least one argument is on the command line but it prints a segmentation fault when no argument is entered and still scans when more than one are.
help?
if(argc == 2);
is equivalent to
if(argc == 2)
;
You need to remove the ; to have the block after this be executed conditionally
if(argc == 2)
// ^ no trailing ; now
{
sscanf(argv[1], "%lf", &a); // now only executed if argc == 2

Build a char converter program with argv[]

I am supposed to build a program that takes argv[1] and according to it transforms the characters into lower case or upper case.However I am stuck cuz C cant compare a pointer with a string.Any ideas on how to compare a pointer and a string,i dont want to compare them character by character.
Here is the code
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main (int argc,char *argv[])
{
char c;
if(argc!=2)
printf("Wrong use of program \n");
printf("The Format is Lower or Upper \n");
return -1;
if ((strcmp(argv[1],"Lower"))==0)
{
while((c=getchar())!=EOF)
{
printf("-");
putchar(tolower(c));
printf("\n");
}
}
if ((strcmp(argv[1],"Upper"))==0)
{
while((c=getchar())!=EOF)
{
printf("-");
putchar(toupper(c));
printf("\n");
}
}
if ((strcmp(argv[1],"Lower"))!=0 && ((strcmp(argv[1],"Upper"))!=0))
{
printf("Wrong use of program \n");
printf("The Format is Lower or Upper \n");
return -1;
}
return 0;
}
What you want to do is use the function strcmp or stricmp (for case insensitive).
Firstly, use strcmp which will return 0 if the char arrays match.
if (!strcmp(argv[1], "Lower"))
{
Secondly if more than one statement applies to an if condition, the statements must be encased in {}.
if (argc != 2)
{
printf("Wrong use of program \n");
printf("The Format is Lower or Upper \n");
return -1;
}

Resources