C 在输入字符串中按特定计数打印字符,甚至不存储整个字符串

C 在输入字符串中按特定计数打印字符,甚至不存储整个字符串,c,string,C,String,问题-我想打印输入字符串中第5个位置的字符,如果用户继续键入他想要的字符串,一旦按下enter键,第5个位置的字符将自动打印。这里的关键是我们不需要将字符串存储在内存中。 我编写了这个特殊的代码,其中也包括测试用例部分 #include<stdio.h> #define c 5 char flush() { int d = c; char temp, temp1; while(1) { temp = getchar(); if(temp == '\n') br

问题-我想打印输入字符串中第5个位置的字符,如果用户继续键入他想要的字符串,一旦按下enter键,第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;
}
#包括
#定义C5
字符刷新()
{
int d=c;
字符温度,temp1;
而(1)
{
temp=getchar();
如果(临时=='\n')
打破
如果(d==0)
temp1=temp;
}
返回温度;
}
int main()
{
int max;
charele,pre;
扫描频率(“%d”和最大值);
fflush(stdin);
ele='\n';
而(最大--)
{
pre=ele;
ele=flush();
如果(pre='\n'&&ele='\n')
打破
printf(“%c\n”,ele);
}
返回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);
}
#包括
int main()
{
char ch=getchar();//接受字符输入
焦炭温度;
int i=0;//计算字符数
while(ch!='\n')//在回车时停止循环
{
i++;
如果(i==5)
temp=ch;//第五个字符
ch=getchar();
}
printf(“%c\n”,temp);
}

在上面的示例中,程序字符串未存储在任何变量中,第五个字符在enter上打印。

OK。计算字符数直到达到5,然后打印出字符并重置计数。简单..当删除它们时,
d
c
pre
temp1
等有什么意义?编辑我的问题,如果您能帮我调试我的代码,我将更加感激。:)1) 应使用
intr ch
EOF
与所有其他
char
区分开来,然后
while(ch!='\n'&&ch!=EOF)
2)如果
ch='\n'
在第五个
char
之前,则
temp
未定义。最好将其设置为默认值
char temp='?'