Home > Enterprise >  how to set equal two character values I tried but I cannot do it it compiled but don't support
how to set equal two character values I tried but I cannot do it it compiled but don't support

Time:09-27

#include<stdio.h>

void main(){
    
     char marital[5];
     printf("enter your marital details-");
     scanf("%s",&marital);

     if(marital=="male"){        
        printf("you are insured");
     }
}

CodePudding user response:

There are a couple of issues in your code:

  • main() should not return void. Its proper return value in an int.
  • You don't need to pass the address of marital to scanf() since strings in C are just pointers to arrays of char.
  • scanf() is a dangerous function. You should not use it to read user input. Use fgets() function, it reads an entire line and is much safer.
  • if(marital=="male") you are basically comparing two pointers, not the actual strings. You have to use strcmp().

That said, here's how your code should be:

#include <stdio.h>
#include <string.h> // for strcmp()

int main()
{
    char marital[5];
    printf("Enter your marital details: ");
    fgets(marital, sizeof marital, stdin);
    marital[strcspn(marital, "\n")] = `\0`; // fgets reads \n too so remove it

    if(strcmp(marital, "male") == 0)
        printf("you are insured");
}

CodePudding user response:

You should use strcmp()to compare char arrays (strings) in C Programming Language. Also remember to add the string ending char '\0'.

#include <unistd.h>
#include <string.h>

#define INSURED "You are insured\n"
int main () {
        char marital[5];

        int n = read(0, marital, 5);
        marital[n - 1] = '\0';

        if ( strcmp(marital, "male") == 0 ) {
                write(1, INSURED, strlen(INSURED));
        }

        return 0;
 }

strcmp() returns an integer

  • 0 if strings are equal

  • > 0 if the first non-matching character in str1 is greater (in ASCII) than that of str2.

  • < 0 if the first non-matching character in str1 is lower (in ASCII) than that of str2.

CodePudding user response:

char gender[7];

scanf("%s",&gender);
char *message=(!strcmp(gender,"male"))?"gender is male":"gender is female";
printf("%s\n",message);
  •  Tags:  
  • c
  • Related