我正在阅读这本书,并且已经找到了一些我不确定如何从第1章开始测试的例子。他们让你读行并寻找不同的字符,但我不知道如何测试C中的代码我做了。
例如:
/* 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;
}
我不知道如何创建一个具有不同行长度的文件来测试它。在做了一些研究后,我看到有人试着这样做:
[arch@voodo kr2]$ gcc -ansi -pedantic -Wall -Wextra -O ex_1-17.c
[arch@voodo 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
[arch@voodo kr2]$
但我不知道他是如何管理它的。任何帮助将不胜感激。
答案 0 :(得分:2)
该程序读取标准输入。如果您只键入该示例中显示的内容,您将看到相同的输出。输入^D
即可结束您的计划。
答案 1 :(得分:2)
for(i = 0; ((c = getchar()) != EOF) && c != '\n' && i < max - 1; ++i)
这一行告诉您有关getline()函数的所有信息。
它将逐个字符地读取并将其存储在数组中,直到:
max - 1
。否则他们不会被复制。在您的示例中,max = 1000因此仅输入999个字符。