我已经坚持了一段时间,将不胜感激。
我试图一次反向输入一行,但最后全部显示出来。
Eg Input = abc 123
lorem ipsum
dolor sit amet
Output = 321 cba
muspi merol
tema tis rolod
这是我到目前为止的内容,但是它只会反转输入的最后一行。我的想法是我可能不会阅读所有输入内容,但是不确定如何补救?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverse(char *input, int length){
for(int i = length-1; i >= 0; i--){
printf("%c", input[i]);
}
}
int main(void){
char input[100];
while(!feof(stdin)){
fgets(input, 100, stdin);
}
reverse(input, strlen(input));
return 0;
}
如评论中所述,
您放入while循环中的所有内容都会针对每一行执行。您放置在while循环之外的任何内容都只会执行一次。
因此将您的可逆代码与fgets
一起放入循环中。
尝试一下,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverse(char *str)
{
int i,j,length;
char ch;
for(length=0;str[length]!='\n'&&str[length]!='\0';length++); //for length of string litrel between '\n' or '\0' not for full length of the string
for(i=0,j=length-1;i<length/2;i++,j--) //to reverse string
{
ch=str[i];
str[i]=str[j];
str[j]=ch;
}
if(str[length]=='\n') //if the string literal is present
reverse(&str[length+1]); //then goes to recursion
else
return; //if no more string is present then return
}
int main(void)
{
char input[100];
int i;
memset(input,'\0',sizeof(input)); // initialize to null
for(i=0;!feof(stdin);i=strlen(input))
{
fgets(&input[i],(100-i), stdin); // &input[i] is to merge the inputting string to the before string present in the char input[100];
}
input[strlen(input)-1]='\0';
reverse(input);
printf("\n%s",input);
return 0;
}
输入:
abc 123
lorem ipsum
美元坐amet
ctrl + z
注意:ctrl + z用于在Windows中将EOF发送到stdin,它必须在新行中。
cmd输出:
abc 123
lorem ipsum
dolor sit amet
^Z
321 cba
muspi merol
tema tis rolod
Process returned 0 (0x0) execution time : 11.636 s
Press any key to continue.
注意:在此代码执行中,按Enter键后无法擦除(退格)。如果您想更改输入逻辑。
见下文:
将存储的输入字符串将类似于
"abc 123\nlorem ipsum\ndolor sit amet\0"
反向函数仅反转新行('\ n')字符之间的字符串。如果存在null('\ 0'),则该函数将返回,否则该函数将继续递归。
第一遍:
"321 cba\nlorem ipsum\ndolor sit amet\0"
[321 cba之后有一个'\ n',因此该函数将'\ n'的下一个字符的引用传递给同一函数(递归)。
第二遍:
"321 cba\nmuspi merol\ndolor sit amet\0"
'\ n'存在,因此进行递归。
第三张:
"321 cba\nmuspi merol\ntema tis rolod\0"
'\ n'不存在,所以函数返回。