I'm creating a program to reverse lines (each character) using getchar
.
This is what I've got so far (my code is a bit messy since I'm a beginner).
#include <stdio.h>
#define MAX_CH 256
int main(void)
{
int ch = 0;
int i = 0;
int string[MAX_CH] = {0};
while (ch != '\n')
{
ch = getchar();
string[i] = ch;
++i;
}
i = i - 2; // put i back to the position of the last character
int limit = i;
int n;
int reverse[MAX_CH] = {0};
for (n = 0; n <= limit; ++n)
{
reverse[n] = string[i];
--i;
}
for (n = 0; n <= limit; ++n)
{
printf("%c", reverse[n]);
}
return 0;
}
This code however only works for 1 line. I want to upgrade it to be able to read and print the reverse text immediately after and work for multiple lines until it reaches EOF. How can I do that? I tried putting 1 bigger loop while (ch != EOF)
outside while (ch != '\n')
but that didn't work.
Thanks for helping in advance.
while(ch != '\n')
block or all the following code that reverses the line too? You need to post the code that doesn't work. – Dave Rageri < MAX_CH
andch != '\n'
andch != EOF
– wildplasser