我想将变量中的字符放入C语言中的字符数组中。另外,如您所见,我也想在此后打印反转的数组,但这不是问题。

这是到目前为止我得到的代码:

作为标准输入,我使用带有“

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

int main()
{
  int counter = 0;
  char character_array[57];
  int i = 0;
  int j = 0;
  char character = 0;

  // While EOF is not encountered read each character
  while (counter != EOF)
  {
    // Print each character
    printf("%c", counter);
    // Continue getting characters from the stdin/input file
    counter = getchar(stdin);
    // Put each character into an array
    character_array[j] = { counter };
    j = j + 1;
  }

  // Print the array elements in reverse order
  for (i = 58; i > 0; i--)
  {
    character = character_array[i];
    printf("%c", character);
  }

  return 0;
}


我的IDE在第一个大括号“期望的表达式”后的第35行说。

// Put each character into an array
    character_array[j] = { counter };


所以我猜那里失败了。我想我不能只是将像这样的字符变量放入数组中?否则我该怎么做?

PS:我是C的新手。

最佳答案

删除该行中的{},使其看起来像:

character_array[j] =  counter ;


改进的代码:

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

int main()
{
  int counter = 0;
  char character_array[57];
  int i = 0;
  int j = 0;
  //char character = 0; Unused variable

  // While EOF is not encountered read each character
  while ((counter = getchar()) != EOF)
  {
    // Print each character
    printf("%c", counter);
    character_array[j] = counter;
    j++;
  }
  for (i = j - 1; i >= 0; i--) /* Array indices start from zero, and end at length - 1 */
  {
    printf("%c", character_array[i]);
  }
}

关于c - 如何将变量中的字符放入C语言的数组中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26930969/

10-09 08:38