1

I am writing C program that reads input from the standard input a line of characters.Then output the line of characters in reverse order.

it doesn't print reversed array, instead it prints the regular array.

Can anyone help me? What am I doing wrong?

main()
{

    int count;
    int MAX_SIZE = 20;
    char c;
    char arr[MAX_SIZE];
    char revArr[MAX_SIZE];

    while(c != EOF)
    {
        count = 0; 
        c = getchar();
        arr[count++] = c;

        getReverse(revArr, arr);

        printf("%s", revArr);

        if (c == '\n')
        {
            printf("\n");
            count = 0; 
        }
    }
}


void getReverse(char dest[], char src[])
{


    int i, j, n = sizeof(src); 

    for (i = n - 1, j = 0; i >= 0; i--)
    {
        j = 0;
        dest[j] = src[i];
        j++;    
    }
}
10
  • In your loop you always have j=0. So only first element of dest ever changes. Commented May 30, 2013 at 4:31
  • 3
    For your benefit and ours, please fix your indentation. Commented May 30, 2013 at 4:31
  • 3
    sizeof(src) in C does not work the way you expect it is Commented May 30, 2013 at 4:32
  • you should define a function void getReverse(char dest[], char src[]) which fills dest[] with the characters in src[], in reverse order. Commented May 30, 2013 at 4:32
  • 2
    It would be easier to print the array in reverse directly than to reverse it first and then print that. Commented May 30, 2013 at 4:32

6 Answers 6

4

You have quite a few problems in there. The first is that there is no prototype in scope for getReverse() when you use it in main(). You should either provide a prototype or just move getReverse() to above main() so that main() knows about it.

The second is the fact that you're trying to reverse the string after every character being entered, and that your input method is not quite right (it checks an indeterminate c before ever getting a character). It would be better as something like this:

count = 0;
c = getchar();
while (c != EOF) {
    arr[count++] = c;
    c = getchar();
}
arr[count] = '\0';

That will get you a proper C string albeit one with a newline on the end, and even possibly a multi-line string, which doesn't match your specs ("reads input from the standard input a line of characters"). If you want a newline or file-end to terminate input, you can use this instead:

count = 0;
c = getchar();
while ((c != '\n') && (c != EOF)) {
    arr[count++] = c;
    c = getchar();
}
arr[count] = '\0';

And, on top of that, c should actually be an int, not a char, because it has to be able to store every possible character plus the EOF marker.

Your getReverse() function also has problems, mainly due to the fact it's not putting an end-string marker at the end of the array but also because it uses the wrong size (sizeof rather than strlen) and because it appears to re-initialise j every time through the loop. In any case, it can be greatly simplified:

void getReverse (char *dest, char *src) {
    int i = strlen(src) - 1, j = 0;
    while (i >= 0) {
        dest[j] = src[i];
        j++;
        i--;
    }
    dest[j] = '\0';
}

or, once you're a proficient coder:

void getReverse (char *dest, char *src) {
    int i = strlen(src) - 1, j = 0;
    while (i >= 0)
        dest[j++] = src[i--];
    dest[j] = '\0';
}

If you need a main program which gives you reversed characters for each line, you can do that with something like this:

int main (void) {
    int count;
    int MAX_SIZE = 20;
    int c;
    char arr[MAX_SIZE];
    char revArr[MAX_SIZE];

    c = getchar();
    count = 0;
    while(c != EOF) {
        if (c != '\n') {
            arr[count++] = c;
            c = getchar();
            continue;
        }
        arr[count] = '\0';
        getReverse(revArr, arr);
        printf("'%s' => '%s'\n", arr, revArr);
        count = 0;
        c = getchar();
    }

    return 0;
}

which, on a sample run, shows:

pax> ./testprog
hello
'hello' => 'olleh'
goodbye
'goodbye' => 'eybdoog'
a man a plan a canal panama
'a man a plan a canal panama' => 'amanap lanac a nalp a nam a'
Sign up to request clarification or add additional context in comments.

6 Comments

You are saying this should be my for loop?
for (i = n - 1; i <= j; i--)
I only want this program to end at EOF. but i want it to return answer when I go to new like.
e.g.) entering "hello" should print "olleh" in the next line directly below hello. and now the program should leave one line empty, and should be ready to take next input. It should not terminate after only one line of input. it should not stop till i press (^d) EOF, and it should return reversed array after hit enter.
@Mike, then you need to re-engineer the input loop. Your stated problem was that the characters weren't being reversed an I have fixed the function to achieve that. This is not a "do my work for me" site, we are here to provide assistance. I'll add a loop to achieve what you want but that really should have been a separate question.
|
3

Your 'count' variable goes to 0 every time the while loop runs.

Comments

1
  • Count is initialised to 0 everytime the loop is entered
  • you are sending the array with each character for reversal which is not a very bright thing to do but won't create problems. Rather, first store all the characters in the array and send it once to the getreverse function after the array is complete.
  • sizeof(src) will not give the number of characters. How about you send i after the loop was terminated in main as a parameter too. Ofcourse there are many ways and various function but since it seems like you are in the initial stages, you can try up strlen and other such functions.
  • you have initialised j to 0 in the for loop but again, specifying it INSIDE the loop will initialise the value everytime its run from the top hence j ends up not incrmenting. So remore the j=0 and i=0 from INSIDE the loop since you only need to get it initialised once.

Comments

0

check this out

#include <stdio.h>
#include <ctype.h>

void getReverse(char dest[], char src[], int count);

int main()
{
  // *always* initialize variables
  int count = 0;
  const int MaxLen = 20; // max length string, leave upper case names for MACROS
  const int MaxSize = MaxLen + 1; // add one for ending \0
  int c = '\0'; 
  char arr[MaxSize] = {0};  
  char revArr[MaxSize] = {0};

  // first collect characters to be reversed
  // note that input is buffered so user could enter more than MAX_SIZE
  do
  {
    c = fgetc(stdin);
    if ( c != EOF && (isalpha(c) || isdigit(c))) // only consider "proper" characters
    {
      arr[count++] = (char)c;
    }
  }
  while(c != EOF && c != '\n' && count < MaxLen); // EOF or Newline or MaxLen

  getReverse( revArr, arr, count );

  printf("%s\n", revArr);

  return 0;
}

void getReverse(char dest[], char src[], int count)
{
  int i = count - 1;
  int j = 0; 

  while ( i > -1 )
  {
    dest[j++] = src[i--];
  }
}

Comments

0

Dealing with strings is a rich source of bugs in C, because even simple operations like copying and modifying require thinking about issues of allocation and storage. This problem though can be simplified considerably by thinking of the input and output not as strings but as streams of characters, and relying on recursion and local storage to handle all allocation.

The following is a complete program that will read one line of standard input and print its reverse to standard output, with the length of the input limited only by the growth of the stack:

int florb (int c) { return c == '\n' ? c : putchar(florb(getchar())), c; }
main() { florb('-'); }

Comments

0

..or check this

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
char *my_rev(const char *source);

int main(void)
{
char *stringA;
stringA = malloc(MAX);    /* memory allocation for 100 characters */
if(stringA == NULL)        /* if malloc returns NULL error msg is printed and program exits */
    {
    fprintf(stdout, "Out of memory error\n");
    exit(1);
    }
else
    {    
    fprintf(stdout, "Type a string:\n");
    fgets(stringA, MAX, stdin);
    my_rev(stringA);
    }
return 0;
}
char *my_rev(const char *source)    /* const makes sure that function does not modify the value pointed to by source pointer */
{
int len = 0;                    /* first function calculates the length of the string */
while(*source != '\n')   /* fgets preserves terminating newline, that's why \n is used instead of \0 */  
    {
    len++;
    *source++;
    }
len--;                           /* length calculation includes newline, so length is subtracted by one */
*source--;                   /* pointer moved to point to last character instead of \n */
int b;
for(b = len; b >= 0; b--)    /* for loop prints string in reverse order */
    {
    fprintf(stdout, "%c", *source);        
    len--;
    *source--;
    }
return;
}  

Output looks like this:
Type a string:
writing about C programming
gnimmargorp C tuoba gnitirw

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.