【问题标题】:Replacing a list of values with user input C用用户输入 C 替换值列表
【发布时间】:2021-02-16 19:33:15
【问题描述】:

如何将Numbers 值替换为input。如果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 multidimensional-array copy c-strings string-literals


    【解决方案1】:

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

    #include <string.h>
    
    //...
    
    strcpy( Numbers[input - 1], "K" );
    

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

    【讨论】:

      【解决方案2】:

      我刚刚为你做了这个。

      #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;
      }
      

      【讨论】:

      • 如果您有任何问题,请随时提问。
      猜你喜欢
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2015-01-14
      • 2012-07-30
      • 2014-04-18
      • 1970-01-01
      • 2022-12-01
      相关资源
      最近更新 更多