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;
}
Related
I am attempting to parse a command line argument, which in turn will execute an associated case within a switch statement. When I parse an integer argument (as seen in the code below), the associated case executes correctly. When I attempt to parse a string such as "CPU", I do not get the correct output.
Functioning code (parsing an integer e.g. an argument of 4 gives athe correct output of hello):
#include <stdio.h>
int main(int argc, char *argv[]) {
char execution_mode = atoi (argv[1]);
switch (execution_mode)
{
case (4) :
printf("Hello");
getchar();
break;
case (8) :
printf("Goodbye");
getchar();
break;
default:
printf("Error! execution mode is not correct");
getchar();
break;
}
return 0;
}
My attempt at parsing a string e.g. the argumentCPU:
#include <stdio.h>
int main(int argc, char *argv[]) {
typedef enum MODE { CPU, OPENMP } MODE;
MODE execution_mode = (char)argv[1];
switch (execution_mode)
{
case (CPU) :
printf("Hello");
getchar();
break;
case (OPENMP) :
printf("Goodbye");
getchar();
break;
default:
printf("Error! execution mode is not correct");
getchar();
break;
}
return 0;
}
You cannot convert a string to an enumerate like this. What you're doing is just converting the pointer to the string to char. Which fails.
One alternative (besides comparing first argument with strcmp) to avoid this would be to give a character value to your enumerates:
typedef enum { CPU='C', OPENMP='O' } MODE;
and now you can pick the first letter of the first argument and convert it:
MODE execution_mode = (MODE)argv[1][0];
The letters must be of course all different. And check argc>1 to see if argv[1] is valid, of course
If you want full string match, you have no other choice than using strcmp:
const char *execution_mode = argv[1];
if (strcmp(execution_mode,"CPU")==0)
{
// do something
}
else if (strcmp(execution_mode,"OPENMP")==0)
{
// do something else
}
With the help of the users who have answered this question, I have found a working solution by using strcmp as seen below. I have also added some error checking to ensure enough arguments have been enterred on the command-line.
#include <stdio.h>
int main(int argc, char *argv[]) {
//Ensure there are enough arguments
if (argc < 2)
{
printf("Error: not enough arguments");
exit(1);
}
typedef enum MODE { CPU, OPENMP, CUDA, ALL } MODE;
MODE execution_mode = (MODE)argv[1];
//Compare string with command-line arguments
if (strcmp("CPU", execution_mode) == 0)
{
//selects CPU case
execution_mode = CPU;
}
else if (strcmp("OPENMP", execution_mode) == 0)
{
//selects OPENMP case
execution_mode = OPENMP;
}
else
{
printf("invalid arg");
}
//Switch statement
switch (execution_mode)
{
case (CPU) :
printf("CPU MODE SELECTED");
getchar();
break;
case (OPENMP) :
printf("OPENMP MODE SELECTED");
getchar();
break;
default:
printf("Error: execution mode is not correct");
getchar();
break;
}
return 0;
}
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;
}
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');
I need a help with the following function, it's expecting an integer input; and when I insert something like "F" (non-numerical characters ), the program gets stuck, it doesn't show any output or let me insert more inputs.
how can this be fixed?
int input_legality(int game_board[FIELD_ROWS][FIELD_COLS])
{
int input=0;
while(1)
{
if(scanf("%d", &input)==1)
{
if(input==DOWN || input==LEFT || input==RIGHT || input==UP)
{
return input;
}
else
if(input==EXIT)
{
printf("\n program exited by user \n");
return 1;
}
else
if(input==PRINT)
{
printField(game_board);
continue;
}
else
{
fprintf(stderr,"your step is undefined, please try another one\n");
continue;
}
}
}
return 0;
}
It seems that "F" is left in stdin if scanf() does not read an integer.
One answer would be to scan a string if an integer is not detected...
Try to add something like
char bla[256];
scanf("%s",bla);
At the end of the while loop (or in case scanf("%d) failed)
Here is a basic "main" code :
#include <stdio.h>
#define DOWN 0
#define UP 1
#define LEFT 2
#define RIGHT 3
#define EXIT 4
#define PRINT 5
int input_legality()
{
int input=0;
while(1)
{
if(scanf("%d", &input)==1)
{
if(input==DOWN || input==LEFT || input==RIGHT || input==UP)
{
return input;
}
else{
if(input==EXIT)
{
printf("\n program exited by user \n");
return 1;
}
else{
if(input==PRINT)
{
printf("ble %d \n",input);
continue;
}
else
{
fprintf(stderr,"your step is undefined, please try another one\n");
continue;
}
}
}
}
//while(getchar() != EOF);
//fflush(stdin);
char bla[256];
scanf("%s", bla);
}
return 0;
}
int main ( int argc , char * argv [] )
{
int i;
for(i=0;i<42;i++){
input_legality();
}
return 0;
}
This scanf is the easy way : some other may be better.
Using switch-case may clarify the code.
Bye,
Francis
Always, always, always get (interactive) input a line at a time. That's how the user conceives it, so the program logic should be similar.
The POSIX getline function is very useful. Alternatively, you can use fgets and deal with overlong lines yourself (perhaps implementing getline, since it is pretty easy).
Once you've fetched a line of input, parse it (being sure to error on trailing garbage) using any method: sscanf, strtok_r, strtou?ll?, ...
My aim is to take two strings and compare there ends if both of them ends with "ing","ed" or there ends do not match.It always says that strings do not match .
#include <stdio.h>
#include <conio.h>
#include <string.h>
int ised(char str[]);
int ising(char str[]);
int main()
{
char str1[30],str2[30];
printf("Enter 1st string:\n");
gets(str1);
printf("Enter 2nd string:\n");
gets(str2);
if((ising(str1))||(ised(str1))||(ising(str2))||(ised(str2)))
{
if(ising(str1)&&ising(str2))
{
printf("Both strings end with ing");
}
else if(ised(str1)&&ised(str2))
{
printf("Both strings end with ed");
}
else
printf("Both strings ending do not match");
}
else
printf("One or both strings do not end with ing or ed.Program Quitting...");
getch();
return 0;
}
int ising(char str[])
{
int len,flag=0;
len=strlen(str);
if (!(strncpy(&str[len-3],"ing",3)))
flag=1;
else
flag=0;
return flag;
}
int ised(char str[])
{
int len,flag=0;
len=strlen(str);
if( !(strncpy(&str[len-2],"ed",2)) )
flag=1;
else
flag=0;
return flag;
}
You are using strncpy which does string copying, if you want to compare strings, use strncmp.
See: strncpy
and strncmp
It looks like you're using strncpy when you actually mean to use to strcmp. You're trying to compare the strings, right?
Use strncmp. And if you're slicing strings, don't forget the terminators.
Would be nice to tell us where you're having problems, what you expect and the result you're currently getting.