Maria Vasileiou Maria Vasileiou - 10 days ago 4
C Question

Can printf print defined strings?

Is it possible to scan a character, pass it to a char array and then if a is defined as string to print that string? Below is the code, (which gets the warning "cast to pointer from integer of different size")
Thanks in advance

char *a = "alpha";
int main()
{
char *A[80];
char ch;
printf("enter message");
scanf(" %c", &ch);
A[0] = (char *) ch;
printf("%s\t", A[0]);

return 0;
}

Answer

What you want might be something like this.

#include <stdio.h>

/* word candidate list: terminated by NULL */
const char* a[] = {
    "alpha",
    NULL
};

int main(void)
{
    char ch;
    int i;
    /* read input */
    printf("enter message");
    if (scanf(" %c", &ch) != 1)
    {
        puts("read error");
        return 1;
    }
    /* search for matching word(s) */
    for (i = 0; a[i] != NULL; i++)
    {
        /* if the first character of the word is what is scanned, print the word */
        if (a[i][0]  == ch)
        {
            printf("%s\t", a[i]);
        }
    }
    return 0;
}
Comments