简体   繁体   English

如何在不使用数组或任何库函数(用于反转的任何函数)的情况下反转用户输入?

[英]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?你如何从用户输入一个字符串(一般意义上说,独立于编程)并在 C/C++ 中打印它的反转而不使用数组或任何库函数来反转用户输入?

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 *) .但是对此的所有答案都是使用库函数或使用指向 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++.从技术上讲,这是不可能的,因为字符串在 c 中是一个 char 数组,而在 c++ 中是一个表示 char 数组的对象。

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;
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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