c - C语言中strcpy的使用

标签 c strcpy

好吧,基本上我一直在以 16 名玩家参加锦标赛的形式编写一个程序。我目前正在使用循环编写第一轮的代码,然后尝试将每场比赛的获胜者发送到名为 R2CONTESTANTS 的新数组。但是,当我打印 R2CONTESTANTS 数组中的所有内容时,它仅存储数组中每个其他元素的一半字符串和一半随机字符([1],[3]。任何帮助将不胜感激,被困了几个小时。

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

#define CONTESTANTS 16
#define R2CONTESTANTS 8
#define MATCHNO 8

//Forward Declarations
int R1(char Name [][20]);

int main(void)
{
  GetNames();
  int R1(char Name[][20]);
  return 0;
}

int GetNames(void)
{
  char Name[CONTESTANTS][20];
  int n;


  printf("Hello and Welcome to the 2014 Tennis Knockout Competition!\n");
  printf("Please enter the names of all 16 players (MAX 20 CHARACTERS): \n");

/*Get Names loop*/
  for(n = 0; n < CONTESTANTS ; n++)
    {
      printf("%d >>", n+1);
      scanf("%20s", Name[n]);
      fflush(stdin); 
    }
  R1(Name);
}

int R1(char Name[][20])
{
  int m/*match counter*/, i=0/*PLAYER COUNT*/, n/*TEST*/ ;
  int WinNO;
  char R2Name[R2CONTESTANTS][20];

  printf("Welcome to Round 1!\n");

  for( m = 0 ; m < MATCHNO ; m++, i+=2 ) //PER MATCH
    {
      printf("\nMatch %d of %d.\n", m+1, MATCHNO);
      printf("\n1.   %s   v   2.   %s\n", Name[i], Name[i+1]);
      printf("\nPlease enter number of winner: ");
      scanf("%d", &WinNO);
       /*WINNER/LOSER*/
      switch(WinNO)//STRCPY is sending too many elements to R2CONTESTANTS array.
        {
          case 1:
          strcpy(R2Name[i], Name[i]);
          //printf("%s is sent through to the next round.\n", Name[i]);
          break;
          case 2:
          strcpy(R2Name[i], Name[i+1]);
          //printf("%s is sent through to the next round.\n", Name[i+1]);
          break;
          default: 
          printf("something went wrong\n"); //IMPROVE
          break;
      }


     }
  //TEST
  for(n = 0 ; n < R2CONTESTANTS ; n++)
  {
      printf("Winner %d: %s\n", n+1, R2Name[n]);
  }
}

这就是 R2CONTESTANTS 中的内容:

获胜者 1:a
获胜者 2: �
获胜者 3:c
获胜者 4:
获胜者 5:e
获胜者 6: �
获胜者 7:g
获胜者 8: �

最佳答案

问题是您要复制到 R2Name[i] 中,但每次迭代 i 都会增加 2,因此只有 R2Name[0]、R2Name[2] 等被填写。 m 每次仅增加 1,因此您可以复制到 R2Name[m],这应该可以解决问题。

关于c - C语言中strcpy的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27007671/

相关文章:

c - 使用 AVR-C 迭代 float 中的数字

python - 换屏事件

c++ - C中的静态和C++中的静态之间的区别??

可以使用 strcpy 但不能使用 strcat 的情况

c - 将变量添加到文件路径

c - 如何在文件*流中的特定点停止并扫描某些值?

c - 具有相同名称和类型的两个变量,在两个不同的 .c 文件中,使用 gcc 编译

C 中将一个字符从一个字符数组复制到另一个字符数组

C++:追加到 vector 字符串