因此,我正在編寫一個C語言練習程序,其目的是獲取用戶輸入,然後在到達EOF後,讀回輸入,但只讀取超過10個字符。只打印長度超過10個字符的輸入行(ANSI C)
我在Linux上,所以EOF是Ctrl + D,但是,如果輸入行長度超過10,它會在我按下Enter時打印,而不是等到EOF達到。
這裏是我的代碼:
#define MAXSIZE 1000
#define SIZE 10
int checklen(char line[], int index);
int main()
{
char currentline[MAXSIZE];
int i = 0;
while ((currentline[i] = getchar()) != EOF){
if (currentline[i] == '\n'){
if (checklen(currentline, i) > SIZE){
printf("%s", currentline);
}
}
++i;
}
return 0;
}
int checklen(char line[], int index)
{
int i;
for (i=index; line[i] != '\n'; ++i){
;
}
return i;
}
編輯:我一直在努力,現在沒有運氣弄清楚了好一陣子。我不是很瞭解你們在說什麼,但是我們最終會到達那裏:)
我已經重寫了代碼,但它仍然無法正常工作。
#include <stdio.h>
#define MAX 1000
#define SIZE 10
void examine(char input[], int index);
int main()
{
int i=0;
char input[MAX];
char output[MAX];
//take user input and store it in our input string
while ((input[i] = getchar()) != EOF){
++i;
}
//put a null byte at the end of input[]
input[i+1] = '\0';
//examine line by line until end of string (null byte)
for (i=0; input[i] != '\0'; ++i){
if (input[i] == '\n'){
examine(input, i);
}
}
return 0;
}
void examine(char input[], int index)
{
//decrement through input[] until \n or start [0] is reached
int i=0;
for (i=0; ((input[index] != '\n') || (index > 0)); ++i){
--index;
}
//if line is bigger than 10 chars, print it
if (i>SIZE){
for (; input[index+1] != '\n'; ++index){
putchar(input[index]);
}
}
//otherwise, return
return;
}
剛剛意識到這是因爲我的printf是在if語句中。現在我只需要找到解決方法... –
'EOF'不是'char',它是'int'! – mafso
如果你確實不希望在輸入完成後才顯示任何輸出,那麼當你遇到換行符時,你將不得不保存每個有效的(足夠長的)行,然後在讀取循環之後,你將會有掃描保存行的列表。隨時隨地產生輸出要簡單得多,而且更經濟實惠。 –