Reputation: 437
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.
Upvotes: 0
Views: 15322
Reputation: 20244
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]);
}
}
Upvotes: 0