简体   繁体   中英

How to reverse a user input without using array or any library function(any function for reversing)?

Let me clear you first that I'm not a college student and this is not my home assignment. I am just curious to know the solution of this question which was once asked to me. I think this is a nice and tricky question which I feel worth sharing.The question was--

How do you input a string(said in general sense, independent of programming) from a user and print reverse of it in C/C++ without using array or any library function for reversing the user input?

I am unable to break-into this. Help please

Note: Members are marking it as a duplicate for this question. But All answers to this are either using library functions or using a pointer to char array(char *) . None of them is allowed in my case. Please review it once again

You can try recursion.

void print_reverse_str() {
  int c = getchar();
  if (c != EOF) {
    print_reverse_str();
    putchar(c);
  }
}

Technically this is impossible because a string is a char array in c and an object representing a char array in c++.

I hope you meant not using arrays directly.

So try this pointer based solutions :

void strrev(char *str)
{
        if( str == NULL )
                return;

        char *end_ptr = &str[strlen(str) - 1];
        char temp;
        while( end_ptr > str )
        {
                temp = *str;
                *str++ = *end_ptr;
                *end_ptr-- = temp;
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM