Josh Salecich Josh Salecich - 1 year ago 80
C Question

In C turning a char into a string

I am reading from a file using

and doing that makes it so that I have a char. However, I want to convert this char to a string such that I can use the
function upon it. How would I go about doing this?

int xp;
while(1) {
xp = fgetc(filename);
char xpchar = xp;
//convert xpchar into a string

Answer Source

Simply create an array with two items, your character and the null terminator:

char str[] = {ch, '\0'};

Or if you will, use a compound literal to do the same:

(char[]){ch, '\0'}

Compound literals can be used to convert your character directly, inside an expression:

printf("%s", (char[]){ch, '\0'} );