2014-09-30 106 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