反转打印功能

Function to reverse print

昨天我不得不解决一个考试练习,不幸的是,我失败了.. 练习是使用以下规则在 C 中创建一个函数:

根据这些信息,我写道:

int     ft_strlen(char *str) /*to count the length of the original string*/
{
    int     i;
    i = 0;
    while (str[i])
            i++;
    return (i);
}
char    *ft_rev_print (char *str)
{
    int     i;

    i = ft_strlen(str);
    while (i)
    {
            write (1, (str +1), 1);
            i--;
    }
    return (str);             /*returning its argument */
}

int     main(void)     /*IT HAD TO WORK WITH THIS MAIN, DID NOT WROTE THIS MYSELF!*/
{
    ft_rev_print("rainbow dash");
    write(1, "\n", 1);
    return (0);
}

我尝试了很长时间让它工作,但失败了..所以现在我为此伤透了脑筋。我做错了什么 ?我错过了什么?

提前致谢!

您的 while 循环是错误的,您从 i=0 开始并在它不为零时进行迭代,因此不会进行任何迭代。

你应该做的是:

  • 初始化 i 使其成为最后一个字符的索引
  • 循环,只要它是一个有效的索引
  • 打印第 i 个字符,不总是第二个(在索引 1 处)
char *ft_rev_print (char *str)
{
    int i;

    i = ft_strlen(str) - 1; // <-- Initialize i to be the index of the last character
    while (i >= 0) // <-- Loop as long as it's valid
    {
        write (1, (str+i), 1); // <-- Print the i-th character
        i--;
    }
    return (str);
}

首先,你们的老师不够合格。该函数应至少声明为

char * ft_rev_print( const char *str );
                     ^^^^^

因为传递的字符串在函数内没有改变。

您忘记调用函数 ft_strlen

你的意思好像是

i = ft_strlen( str );

结果这个循环

i = 0;
while (i)
{
    //...
}

永远不会执行,因为最初 i 等于 0 并且循环条件立即计算为 false。

也在这次通话中

write (1, (str +1), 1);
          ^^^^^^^^

您总是试图输出字符串的第二个符号。

另外换行符的输出'\n'根据其描述应该在函数内。

该函数可以如下面的演示程序所示(而不是非标准函数 write 我将使用函数 putchar 但您可以将其替换为write你自己)

#include <stdio.h>

char * ft_rev_print( const char *str )
{
    const char *p = str;
    
    while ( *p ) ++p;
    
    while ( p != str ) putchar( *--p );  // substitute the call of putchar for write( 1, *--p, 1 )
    
    putchar( '\n' );  // substitute the call of putchar for write( 1, "\n", 1 )
    
    return ( char * )str;
}

int main(void) 
{
    ft_rev_print( "rainbow dash" );
    
    return 0;
}

程序输出为

hsad wobniar

您好,我已经尝试过您的问题,有一点我想补充一点,在您的问题中,您已经写下了字符串的长度以及代码中的以下部分:

  write (1, (str +1), 1);

不正确,所以我更正了它,基本上我们是像这样添加前面字符的背面,错误是在 while 循环条件下:

写(1,(str+i),1);

您可以在此处获得完整原型:

char    *ft_rev_print (char *str)
{
    int     i;
     i = ft_strlen(str);//returning the length of string
     while (i>=0)
     {
            write (1,(str+i),1);
            i--;
     }
    return (str);             /*returning its argument */
}