2014-09-30 69 views
0

问题 - 我想在输入字符串中的第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; 
} 

只要问题看起来很简单,当我尝试用这种特殊方式编码问题时,我发现它非常棘手。我怎样才能调试我这个特定的代码?

+0

好的。对字符进行计数直至达到5,然后打印字符并重新计数。简单.. – 2014-09-30 15:00:48

+0

当删除它们时,'d','c','pre','temp1'等等有什么重要意义? – 2014-09-30 15:27:02

回答

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); 
} 

在这里,在上述程序字符串做。

+0

编辑我的问题,我会更感激,如果你通过调试我的代码来帮助我。 :) – lethal 2014-09-30 15:23:13

+0

1)应该使用'intr ch'区分'EOF'和其他所有'char',然后'while while(ch!='\ n'&& ch!= EOF)'2)if ch =='\在第五个'char'之前,'temp'是未定义的。最好将其设置为默认值'char temp ='?';' – chux 2014-09-30 18:00:09