c++stringdev-c++strchr

Using strchr() in dev c++, invalid conversion from 'char' to 'int'[-fpermissive]


i want the character founded by what i'm input to to find it so here's the code, but it's always error in "hasil=strchr(str,karakter);". it's says "invalid conversion from 'char' to 'int'[-fpermissive]"

#include <iostream>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <stdio.h>
using namespace std;

int main(void){
    char str[100];
    char karakter[50];
    char *hasil;
    hasil=strchr(str,karakter);

    cout<<"Input String : "; gets(str);
    cout<<"Input Karakter : "; gets(karakter);
    printf("\nResult : %s\n",hasil);
    printf("karakter %c founded in index %d",karakter,(hasil-str));
    getch();
    return 0;
}

Solution

  • There's multiple problem in your code.

    1. strchr takes a char * as first argument and a char as second argument, you gave a char * instead. Here is the manual http://man7.org/linux/man-pages/man3/strchr.3.html
    2. You should be putting the function call strchr after both gets to initialize both str and karakter
    3. You should be using fgets instead of gets, your program would be killed if the user inputs overflows your buffers

    After the modification it should look like this

        #include <iostream>
        #include <stdlib.h>
        #include <conio.h>
        #include <string.h>
        #include <stdio.h>
        using namespace std;
    
        int main(void){
            char str[100];
            char karakter;
            char *hasil;
    
            cout<<"Input String : "; fgets(str, 100, stdin);
            cout<<"Input Karakter : "; fgets(&karakter, 1, stdin);
            hasil = strchr(str,karakter);
            printf("\nResult : %s\n",hasil);
            printf("karakter %c founded in index %d",karakter,(hasil-str));
            getch();
            return 0;
        }