0

I want to put a character from a variable into a character array in C. Also I want to print the reversed array afterwards as you can see but that's not the issue now.

This is the code I've got so far:

As stdin I'm using a txt-file with "< input.txt" as a command line argument, and it has 57 characters.

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

My IDE says at line 35 after the first curly brace "expected expression".

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

So I guess it fails there. I assume I cannot just put the character variable like that in the array? How would I go about doing this otherwise?

PS: I'm new to C.

4
  • 2
    have you tried to remove the { and } around counter? Commented Nov 14, 2014 at 13:24
  • 1
    character_array[j] = counter; But it is better to use scanf( "%s", character_array ); and read the whole string at once. Note that you character_array array is better to be longer! Commented Nov 14, 2014 at 13:26
  • 2
    and getchar(stdin) --> getchar() Commented Nov 14, 2014 at 13:27
  • Thank you all, removing the curly braces worked! Commented Nov 14, 2014 at 13:27

2 Answers 2

1
character_array[j] = counter;

Just that simple i think

Sign up to request clarification or add additional context in comments.

Comments

0

Remove the { and } in that line so that it looks like :

character_array[j] =  counter ;

Improved code:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.