简体   繁体   中英

C: Change char in string

While this is a basic question, the exact situation is different from average. I have char board[] = {"13572"} that represents a board (the index of the array is the row of the board and the int (represented as a char) is the number of elements in that row. If the user inputs "3 3" that means they want to change the number of elements at index 2 to be 2 (Or as the user sees it change the number of elements in row 3 to 2, also the user believes the index is from 1-4 for Y and 1-7 for X), changing board to {"13272"}. I am having an issue where input can change the value in the selected row to be '/' or '0' instead of the desired value. Any advice is appreciated, the relevant functions are below:

Also, board is a global variable. Changes chars in an array to ints(single digits):

int bd2int (char board[], int index){
    char buff[2] = {board[index],'\0'};
    return atoi(buff);
}

changes the board based on move (char move[3] in format "XY"): I believe the issue is here, when printing the board as a string if index 2 was changed the board will only print to index 1, indicating that a '\\0' was inserted at index 2.

int update(char move[]){
   int x;
   int y;
   x = bd2int(move,0);
   y = bd2int(move,2);
   x--;
   board[y-1] = (char)x;
   totalElements=    bd2int(board,0)+bd2int(board,1)+bd2int(board,2)+bd2int(board,3);
   return 1;
}

Thank you for the assistance, the issue was line board[y-1] = (char)x; I found a more accurate way to convert int x to char x that fixed the issue here: https://stackoverflow.com/questions/1114741/how-to-convert-int-to-char-c

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