【问题标题】:How to put character from variable into array in C?如何将变量中的字符放入C中的数组中?
【发布时间】:2014-11-14 13:20:49
【问题描述】:

我想将变量中的字符放入 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 新手。

【问题讨论】:

  • 您是否尝试删除counter 周围的{}
  • character_array[j] = counter; 但最好使用scanf( "%s", character_array ); 并一次读取整个字符串。请注意,您的 character_array 数组最好更长!
  • getchar(stdin) --> getchar()
  • 谢谢大家,去掉花括号成功了!

标签: c arrays string character


【解决方案1】:
character_array[j] = counter;

就是这么简单

【讨论】:

    【解决方案2】:

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

    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]);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 2023-04-06
      • 2019-08-14
      • 1970-01-01
      • 2020-12-11
      • 2022-07-25
      相关资源
      最近更新 更多