简体   繁体   中英

How do I print int into array variable of char type in C?

Input maze:

##..##############
##..............##
########..########
##........##....##
##..########..####

Output expected:

##00##############
##++02++04++06++##
########++########
##++08++06##----##
##10########--####

here I have stored maze as 2d array into structure as:

struct mazecells{
    char symbol;
    int reachable;
    int visited;
    int clear;
    int costs;
};

typedef struct maze {
    struct mazecells M[BUFFERSIZE][BUFFERSIZE];
    int startx, starty;
    int numrows, numcolumns;
    int initdir;
}maze_t

so whenever my program traverse through maze path ie '.' , I have assigned cost to that path using maze->M[pos.y][pos.x].costs = <cost_value> .
Now while printing output as shown above, I need to print the cost value instead of maze symbol. I have written below code but it is printing some random junk characters. How can I achieve it.

    if (maze->M[i][j].costs !=0)
    {
        printf("%c",  '0');
        printf("%c",  maze->M[i][j].costs);
    }

it's giving below output:

##++##############
##0☺0☻0♥0♦0♣0♠0##
########0♣########
##0     00♠##....##
##++########..####

If you want to translate the number in "cost" to string, you must use one of: 1. Use %d instead of %c. 2. Use the ascii table and convert your number to char. 3. Use %s with itoa funtion. Actually you were printing ascii code of the number (cost) but not the number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM