编程以获取输入并输出相反的输出:
#define MAX 1000
int readtext(char[],int); /*used to store text in array and
returns the size of the line*/
void reverse(char[]); /*used to reverse the text in the line and
returns 0*/
int main(void)
{
char text[MAX];
printf("Enter text, press Ctrl+d when done \n"); /*prompt user input*/
while((redtext(text, sizeof text)>0)) /*loop repeats until text size is >0*/
{
reverse(text);
printf("%s\n\n",text);
}
return 0;
}
int readtext(char a[],int len)
{
int letchar,i;
for(i=0;i<len-1 && (letchar=getchar())!=EOF && letchar!='\n';i++) /*for loop repeats until end of line*/
a[i]=letchar;
if(letchar=='\n') /*checks if letchar is \n. if true, changes it to null and returns i value*/
a[i++]=letchar;
a[i]='\0';
return i;
}
void reverse(char a[])
{
char t;
int x,y;
for(y=0;a[y]!='\0';y++) /*loop used to get the last element of the array*/
--y;
for(x=0;x<y;x++) /*loop used to reverse the array 'a'*/
{
t=a[x];
a[x]=a[y];
a[y]=t;
--y;
}
}
预期输入/输出:
happy birthday
yadhtrib yppah
我收到此错误消息,但不知道这意味着什么:
/tmp/ccA71SDX.o: In function `main':
1-19.c:(.text+0x63): undefined reference to `redtext'
collect2: ld returned 1 exit status
答案 0 :(得分:0)
你在函数调用中犯了一个错误(redtext
而不是readtext
)。但是你可以使用我的解决方案:
#include <stdio.h>
#include <strings.h>
#define MAXSTRLEN 256
void Reverse(char* str);
int main()
{
printf("Enter string below:\n");
char str[MAXSTRLEN];
fgets(str, MAXSTRLEN, stdin);
Reverse(str);
printf("Result:\n%s\n", str);
return 0;
}
void Reverse(char* str)
{
char tmp;
int length = strlen(str) - 1;
int i;
for(i = 0; i < length / 2; i++)
{
tmp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = tmp;
}
}