First up: sincere apologies for bringing up such a basic problem requesting attention. I intend to reverse a char array with a user input string by using getchar() & display its reverse using putchar(). [I understand that there may be easier or more elegant ways using printf() & scanf(), but I am keen to find the flaw in my logic below with getchar() & putchar():]
#include <stdio.h>
#include <stdlib.h>
#define EOL '\n';
/* Reversing a character array */
int main()
{
int arr_char[10];
int i=0;
/* reading char elements into the array */
printf("Please input the array\n");
arr_char[0]= getchar();
while(arr_char[i]!= EOL && i<=9)
{
i=i+1;
arr_char[i]=getchar();
printf("\ni=%d\n",i);
}
/* display reverse */
while(i>=0)
{
putchar(arr_char[i]);
i--;
}
return 0;
}
1) I get an error message:
reversing char array\main.c|15|error: expected ')' before ';' token|
||=== Build finished: 1 errors, 0 warnings (0 minutes, 0 seconds) ===|
FYI: Line 15 is the
while(arr_char[i]!= EOL && i<=9)
2) I am also trying to print the counter "i" as to see whether it is being incremented on pressing "Enter" after a character is input and it seems that it does.
3) I have defined the arr_char array as
int arr_char[10];
with the intention that if someone inputs "-1" as EOF/EOL, then a char array will perhaps not be of much help. Am I right?
Any explanations in helping get my bearings back on'll be greatly appreciated. Thanks!
#define
and how they work. Hint: They do not require a semicolon to terminate the replacement text.EOF
(not necessarily-1
!).ctrl-D
is the Unix-key to closestdin
actually. Note this is not "end of field", but "end of file"! Any field-seperator is application-specific (newline is a typical example for text, e.g.)printf("Please input the array\n"); int ch; while (i < sizeof arr_char && (ch = getchar()) != EOL && ch != EOF) { arr_char[i++]=ch; } while(i>0) { putchar(arr_char[--i]); };