gpt4 book ai didi

c - 打印输入字符串中一定数量的字符,甚至无需存储整个字符串

转载 作者:行者123 更新时间:2023-11-30 17:28:07 25 4
gpt4 key购买 nike

问题 - 我想打印输入字符串中第 5 个位置的字符,用户在其中继续输入他想要的字符串,一旦按下回车键,字符出现在第 5 个位置将自动打印。这里的关键是我们不需要将字符串存储在内存中。我编写了这个特定的代码,其中也包括测试用例部分。

#include<stdio.h>
#define c 5
char flush()
{
int d = c;
char temp, temp1;
while(1)
{
temp = getchar();
if(temp == '\n')
break;
if(d == 0)
temp1 = temp;
}
return temp;
}
int main()
{
int max;
char ele, pre;
scanf("%d", &max);
fflush(stdin);
ele = '\n';
while(max--)
{
pre = ele;
ele = flush();
if(pre == '\n' && ele == '\n')
break;
printf("%c\n", ele);
}
return 0;
}

就问题看起来很简单而言,当我尝试以这种特定方式编码问题时,我发现它非常棘手。我如何调试我的这个特定代码?

最佳答案

您可以通过以下程序来完成

#include <stdio.h>
int main()
{
char ch=getchar(); //taking character input
char temp;
int i=0; // Count the character
while(ch!='\n') // Stop the loop at enter
{
i++;
if(i==5)
temp=ch; //Fifth character
ch=getchar();
}
printf("%c\n",temp);
}

在上面的程序中,字符串没有存储在任何变量中,第五个字符在输入时打印。

关于c - 打印输入字符串中一定数量的字符,甚至无需存储整个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26123992/

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