问题描述
昨天我不得不解决一个考试练习,不幸的是,我失败了.. 练习是用 C 语言创建一个具有以下规则的函数:
- 编写一个函数,该函数接受一个字符串并反向显示该字符串 顺序后跟换行符。
- 它的原型是这样构造的:char *ft_rev_print (char *str)
- 它必须返回它的参数
- 只允许使用函数 'write'(所以不能使用 printf 或其他函数)
我写了这些信息:
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
并且循环的条件立即评估为假。
也在这次通话中
write (1,(str +1),1);
^^^^^^^^
你总是试图输出字符串的第二个符号。
此外,根据其描述,换行符 '\n'
的输出应该在函数内。
该函数可以如下所示,如下面的演示程序所示(而不是非标准函数 write
我将使用函数 putchar
但您可以将其替换为 {{ 1}} 自己)
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;
}
,
嘿,我已经尝试过您的问题,我想补充一点,在您的问题中,您已经在代码中写入了字符串的长度以及以下部分:
metric1_A metric1_B metric2_A metric2_B metric3_A metric3_B
object
1 3.0 NaN 103.0 NaN 34.333333 NaN
2 1.0 3.0 15.0 104.0 15.000000 34.666667
3 1.0 2.0 26.0 50.0 26.000000 25.000000
不正确,所以我更正了它,基本上我们正在添加像这样的先前字符的后面,并且错误处于while循环条件中:
写(1,1);
您可以在此处查看完整原型:
write (1,1);