0

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;
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • 1
    Double check how the function works: https://en.cppreference.com/w/cpp/string/byte/strchr – NathanOliver Oct 08 '19 at 16:17
  • 2
    Also you need to call `strchr` after you get input, otherwise it is meaningless. – NathanOliver Oct 08 '19 at 16:17
  • 3
    I think `strstr(str, karakter)` would be more appropriate, as both inputs are strings. `strchr()` looks for a *single character* and as usual, `int` is used for that character in library functions. Perhaps you meant to check the *first character* as in `strchr(str, *karakter)`. – Weather Vane Oct 08 '19 at 16:20
  • 2
    [Why gets() is so dangerous it should never be used!](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-dangerous-why-should-it-not-be-used) Further using the iostream for output, why would you then turn around and call `gets()` for input? Are you intentionally mixing C/C++? – David C. Rankin Oct 08 '19 at 16:24

1 Answers1

1

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;
    }
SaltyPleb
  • 353
  • 1
  • 5