cpointerschargetcharputchar

Im a beginner to C and getting an error with my code: assignment to char from char * makes integer from pointer without a cast. How could I fix this?


Im trying to write a code that gets vowels from a string and replaces them with a "*" before outputting the changed string using the functions of getchar() and putchar().

char input_char;

input_char = getchar();

while(input_char != EOF) {
    if (input_char == 'a' || 'e' || 'i' || 'o' ||'u') {
        input_char = "*";
    }

    putchar(input_char);

    input_char = getchar();
}

Solution

  • There are two separate issues with your code.

    The first is the error you are seeing in the title:

    "*" implies a C-string, this is a char array [2] with the bytes '*' and '\0' respectively. Because you have accidentally specified a string instead of a character, your line input_char = "*"; is assigning input_char to be the pointer to the first character, instead of the character itself.

    To see how this works, try substituting that line for the following.

    char tmp[2] = "*";
    input_char = tmp[0];
    

    Which is equivalent to what you intended:

    input_char = '*';
    

    The second issue is that your if statement always returns true because the ascii characters are integers greater than zero. The logical OR denotes separate conditions which are independent of the first clause, you must specify that input_char is what's being compared for each condition. A lengthy but correct example is as below:

    if (input_char == 'a' || input_char == 'e' || input_char == 'i' || input_char == 'o' || input_char == 'u') {
    

    As an aside: If you want this to be more readable, iterating through an array is something to research. Happy coding!