用用户输入 C 替换值列表

Replacing a list of values with user input C

如何用 input 替换 Numbers 值。如果 input 为 1,则 Numbers 值将变为 {"K", "2", "3", "4", "5", "6", "7", "8", "9"},然后如果用户 input 为 4,则 Numbers 值将变为更新为 {"K", "2", "3", "K", "5", "6", "7", "8", "9"} 等等。

int main(void)
{
  int input = 0
  char Numbers[][9] = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
  return 0;
  for (int i = 1; i <= 18; i++){
     scanf("%d", &input);    
  }
}

您需要使用标准的 C 字符串函数 strcpy。例如

#include <string.h>

//...

strcpy( Numbers[input - 1], "K" );

在使用该函数之前,您应该检查 input 的值是否大于 0 且不大于 sizeof( Numbers ) / sizeof( *Numbers )

我刚为你做了这个。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
  //Clear screen
  system("cls");
  //Use system("clear"); on *NIX
  int input = 0;
  char number[][9] = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
  char message[60] = "\nEnter position (Enter 99 to exit!):";
  bool run = true; 
  while(run)
  {      
    //Printing out the result...
    printf("\n");
    for (int i = 0; i < 9; i++)
        printf(" %c", number[i][0]);
    printf("\n");
      
    printf("%s", message);
    scanf("%d", &input); 

    //Check if input is within array boundary
    if(input == 99)
    {
        printf("\n\tExiting...Bye :)\n");
        return 0;
    }
    
    bool skip = true;
    //Check number input position
    if(input > 9 || input <= 0)    
    {
        strcpy(message, "\nArray out of bound! Enter new position:");      
        skip = false;
    }

    if(skip)
    {
        //Convert user position to array index
        input = input - 1;

        // Assign 'K' to the selected array index
        // You can't use double quote when assigning, 
        // because the variable was declared as type char, not string.
        number[input][0] = 'K';
        
        strcpy(message, "\nEnter position (Enter 99 to exit!):");
    }
    
    //Clear screen
    system("cls");
    //Use system("clear"); on *NIX
  }
  return 0;
}