gpt4 book ai didi

c - 反转一条线

转载 作者:行者123 更新时间:2023-11-30 21:39:14 24 4
gpt4 key购买 nike

我试图反转字符串(K&R),但是当我尝试在 main 中使用 printf 时,它什么也不输出,但当我尝试在反向函数中使用 printf 并且它有效。令人困惑的是为什么打印发生在反向函数中而不是在主函数中。任何人都可以帮助我吗?

#include<stdio.h>
#define MAXLINE 1000
void reverse(char*);
int getlen(char*,int);
void main()
{
int i=0;
char line[MAXLINE];
printf("\nEnter anything\n");
while((getlen(line,MAXLINE))>1)
{
reverse(line);
}
printf("%s",line);//problem here
}
int getlen(char line[],int len)
{
int c,i=0;
while((c=getchar())!=EOF && c!='\n' && (i<(len-2)))//last two for \n and \0
{
line[i]=c;
++i;
}
if(c=='\n')
{
line[i]=c;
++i;
}

line[i]='\0';
return(i);//returns 1 if nothing is written
}
void reverse(char line[])
{
int i=0,j=0;
char temp;
while(line[i]!='\0')
++i;
--i;
if(line[i]=='\n')
--i;
while(j<i)
{
temp=line[j];
line[j]=line[i];
line[i]=temp;
++j;
--i;

}

}

最佳答案

Print inside the loop

#include<stdio.h>
#define MAXLINE 1000
void reverse(char*);
int getlen(char*,int);
void main()
{
int i=0;
char line[MAXLINE];
printf("\nEnter anything\n");
while((getlen(line,MAXLINE))>1)
{
printf("%s",line);//problem here
reverse(line);
printf("%s",line);//problem here
}

}
int getlen(char line[],int len)
{
int c,i=0;
while((c=getchar())!=EOF && c!='\n' && (i<(len-2)))//last two for \n and \0
{
line[i]=c;
++i;
}
if(c=='\n')
{
line[i]=c;
++i;
}

line[i]='\0';
return(i);//returns 1 if nothing is written
}
void reverse(char line[])
{
int i=0,j=0;
char temp;
while(line[i]!='\0')
++i;
--i;
if(line[i]=='\n')
--i;
while(j<i)
{
temp=line[j];
line[j]=line[i];
line[i]=temp;
++j;
--i;

}

}

测试

$ gcc main.c 
$ ./a.out

Enter anything
backwards
backwards
sdrawkcab

你也可以试试online该代码只需对代码进行很小的修改即可反转字符串。

关于c - 反转一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37523695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com