我编写了一个程序来解决练习2-2的K&R。
#include<stdio.h>
#define MAXLINE 1000
/* write an equivalent loop without using && or || */
int Getline(char s[], int lim);
int main()
{
int len;
char line[MAXLINE];
while ((len = Getline(line, MAXLINE)) > 0) {
printf("%s%15s%d\n", line, "length: ", len);
}
return 0;
}
int Getline(char s[], int lim)
{
int flag = 1;
int i = 0, c = 0;
for (i = 0; flag == 1; ++i) {
if (i < lim - 1) {
if ((c = getchar()) != '\n') {
if (c != EOF) {
;
}
else {
flag = 0;
}
}
else {
flag = 0;
}
}
else {
flag = 0;
}
if (flag == 1) {
s[i] = c;
}
}
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}这个程序是wrong...in一种奇怪的方式。我使用重定向运行这段代码,如
./2-2 <in使用in文件
接这条线。
那么屏幕上的输出就数不胜数了
G长度:1
看起来程序被困在了一个循环中。但是当我停止使用重定向,只需输入,得到这一行。到终端,尽管它仍然是错误的,无数的输出消失了。为什么?
发布于 2018-06-03 08:44:50
问题在于:
for (i = 0; flag == 1; ++i) {
^^^
i will always increment to at least 1
before the for-loop ends
so your function will never return 0不是在for-循环中递增,而是在插入新元素之后才增加。喜欢
if (flag == 1) {
s[i] = c;
++i;
}而不是for-循环,您可以使用while循环,例如:
int i = 0;
while (flag == 1)
{
...
}下一步是去掉标记并使用break insted。比如:
int i = 0;
while (1)
{
if (i >= lim - 1) break;
...
}您的代码将更短,更容易阅读。
发布于 2018-06-03 09:19:34
你的功能也相当复杂。如果您只想从文件中获得重定向的行,将其存储在line中并确保它以nul结尾(并且没有尾随的'\n' --不应该离开存储的字符串),您可以做一些非常简单的事情,比如:
int Getline (char *s, int lim)
{
int i = 0; /* char count - length */
while (i < lim - 1) { /* loop while chars fit */
int c = getchar(); /* getchar */
if (c == EOF) /* validate EOF? */
goto done;
if (c == '\n') /* validate newline */
continue;
s[i++] = c; /* good char, increment len */
}
done:;
s[i] = 0; /* nul-terminate */
return i; /* return length */
}(注意:从你的评论中可以看出以前没有使用过break,那么简单的goto也同样有效)
示例使用/输出
给定包含行"Get this line."的文件
$ ./bin/equivloop <dat/in
Get this line. length: 14(注意:如果存储换行符,则长度为15,输出将位于下一行)
https://stackoverflow.com/questions/50664595
复制相似问题