2012-10-21 288 views
2

我正在閱讀本書,並且遇到了一些例子,我不知道如何從第1章開始測試。他們有你閱讀行並尋找不同的角色,但我不知道如何測試我所做的C代碼。由K&R編寫的C語言編程語言示例CH1

例如:

/* K&R2: 1.9, Character Arrays, exercise 1.17 

STATEMENT: 
write a programme to print all the input lines 
longer thans 80 characters. 
*/ 
<pre> 
#include<stdio.h> 

#define MAXLINE 1000 
#define MAXLENGTH 81 

int getline(char [], int max); 
void copy(char from[], char to[]); 

int main() 
{ 
    int len = 0; /* current line length */ 
    char line[MAXLINE]; /* current input line */ 

    while((len = getline(line, MAXLINE)) > 0) 
{ 
    if(len > MAXLENGTH) 
printf("LINE-CONTENTS: %s\n", line); 
} 

return 0; 
} 
int getline(char line[], int max) 
{ 
int i = 0; 
int c = 0; 

for(i = 0; ((c = getchar()) != EOF) && c != '\n' && i < max - 1; ++i) 
    line[i] = c; 

if(c == '\n') 
    line[i++] = c; 

line[i] = '\0'; 

return i; 
} 

我不知道如何創建具有不同的線路長度,以測試該上的文件。做一些研究,我看到後有人試圖這樣說:

[[email protected] kr2]$ gcc -ansi -pedantic -Wall -Wextra -O ex_1-17.c 
[[email protected] kr2]$ ./a.out 
like htis 
and 
this line has more than 80 characters in it so it will get printed on the terminal right 
now without any troubles. you can see for yourself 
LINE-CONTENTS: this line has more than 80 characters in it so it will get printed on the 
terminal right now without any troubles. you can see for yourself 
but this will not get printed 
[[email protected] kr2]$ 

但我不知道他是如何對其進行管理。任何幫助將不勝感激。

+0

如果您有配套光盤,您可以從該章節的子目錄中的磁盤上的文件中剪切/粘貼數據,然後通過io重定向將其發送到您的程序'bash $ progname WhozCraig

回答

2
for(i = 0; ((c = getchar()) != EOF) && c != '\n' && i < max - 1; ++i) 

這是告訴你一切你需要知道你的getline()函數的行。

它將由字符讀取的字符,並將其存儲在數組中,直到:

  1. 不按^ d在終端上(Linux)的/^Z(WIN)(^ =對照)
  2. 您不要按鍵盤上的「輸入」鍵
  3. 輸入的字符數不應超過max - 1。否則,他們不會被複制。在你的例子中,max = 1000因此只有999個字符被輸入。
+0

感謝人絕對清除它! – soulrain

+0

接受答案或upvoting是SO說「謝謝」的方式:-) –

2

該程序讀取標準輸入。如果您只是鍵入該示例中顯示的內容,則會看到相同的輸出。輸入一個^D以結束您的程序。

+0

謝謝你要檢查出來 – soulrain

+0

要創建文件,只需創建一個.txt文件並將其保存在與程序相同的目錄中即可。有關打開該文件並從中讀取該文件的信息,請查閱第7.5章「文件訪問」。祝你好運 ! – DaveyLaser

+0

酷會檢查出來! – soulrain