2012-10-21 290 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